Tallboy
Tallboy

Reputation: 13417

Rails 5 API mode with ActionDispatch::Cookies

I have a Rails 5 API that I need to use the cookies method for.

I need to store a cookie used by the front-end with some basic user data (not server session state).

I have this in my application.rb

config.middleware.insert_after ActionDispatch::Callbacks, ActionDispatch::Cookies

It shows up properly when I call rake middleware

But this still happens...

NameError (undefined local variable or method `cookies' for #<SessionsController:0x007fe96fd671e8>):

Controller

class SessionsController < ApplicationController

  def login
    ...
    add_login_headers(current_company.id, user.id, user.format_rights)
    ...
  end

  private

  def add_login_headers(company_id, user_id, rights)
    ...

    cookies.permanent[Settings.cookies.app] = {
      value: JSON.generate(company_id: company_id, user_id: user_id, rights: rights),
      secure: true
    }
  end

end

Upvotes: 3

Views: 2319

Answers (2)

dowi
dowi

Reputation: 1045

you need to add this Controller Module:

class ApplicationController < ActionController::API
  include ActionController::Cookies

Upvotes: 6

Tallboy
Tallboy

Reputation: 13417

I've fixed this kind of a ghetto way, just so I don't have to include 50,000 extra helpers.

def cookies
  # helpers not available in --api mode
  request.cookie_jar
end

Upvotes: 8

Related Questions