Reputation: 1909
I'm trying to write an Ember application in Rails 4, and have decided to go with rails-api
for the api controllers, while keeping the application controller intact for a few pages that aren't part of the single-page app. To put it in more concrete terms, here are my controllers:
app/controllers/application_controller.rb
:
class ApplicationController < ActionController::Base
protect_from_forgery
end
app/controllers/sample_controller.rb
:
class SampleController < ApplicationController
# my methods
end
app/controllers/api/v1/api_controller.rb
:
class Api::V1::ApiController < ActionController::Api
include ActionController::MimeResponds
end
app/controllers/api/v1/sample_controller.rb
:
module Api::V1
class SampleController < ApiController
respond_to :json
# my methods
end
end
My application.html.slim
contains the following line:
== render partial: "flash_msgs" unless flash.blank?
The inclusion of which results in the following error:
undefined method 'flash' for #< ActionDispatch::Request:0x007f99f41d8720 >
Per discussion on this thread, it seems that the culprit could be rails-api
, but I'm not entirely convinced given the inheritance I've set up. Any suggestions?
Upvotes: 30
Views: 22396
Reputation: 35
Good Job requires more than ActionDispatch::Flash
middleware.
Here it is described in the official github repo for the API-only Rails applications.
Add these middlewares just in case..
# config/application.rb
module MyApp
class Application < Rails::Application
#...
config.middleware.use Rack::MethodOverride
config.middleware.use ActionDispatch::Flash
config.middleware.use ActionDispatch::Cookies
config.middleware.use ActionDispatch::Session::CookieStore
end
end
Upvotes: 0
Reputation: 537
well, in my case my API mode rails app I had this code in one of my controller:
protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }
due to which handle_unverified_request was getting called that has this small piece of code request.flash = nil
which was raising Undefined method 'flash' for ActionDispatch::Request
for me.
Dealt with it by replacing protect_from_forgery
with skip_before_action :verify_authenticity_token
Upvotes: 0
Reputation: 16431
If you're like me and creating an API on top of an existing application, you can add this to your config/application.rb file:
config.api_only = false
Upvotes: 32
Reputation: 4044
See: https://github.com/plataformatec/devise/issues/2775
Inside devise.rb change
config.navigational_formats = ['*/*', :html]
to:
config.navigational_formats = [:json]
or just [ ]
Upvotes: 34
Reputation: 19128
Not sure but maybe you need to include the ActionDispatch::Flash
middleware to support the flash. Using:
config.middleware.use ActionDispatch::Flash
The docs says:
ActionDispatch::Flash: Supports the flash mechanism in ActionController.
I hope it helps
Upvotes: 49