undefined method `flash' for #<ActionDispatch::Request
Asked Answered
S

3

3

I have stuff with Ruby on Rails 3

I try this simple code

  def index
    flash[:notice] = "ok"
    respond_to do |format|
      format.html # index.html.erb
    end
  end

it does not work

NoMethodError in DashboardsController#index
undefined method `flash' for #<ActionDispatch::Request:0x7fee9329a9d0>

When I try

redirect_to :some_in, :notice => "ok"

in other place (in some_controller.rb) and then print this :notice in .erb I have same error, undefined method `flash'

I'm stuck on this. I used google to search for it but it does not help.

Sulphurous answered 13/1, 2012 at 17:59 Comment(3)
Are you inheriting from ApplicationController which is inheriting from ActionController::Base? For example, does your controller look like: class DashboardsController < ApplicationController at the top?Chalcanthite
Are you using the rails-api gem by chance?Ba
For anyone who is using rails-api, see hereArmor
D
3

In config/applications.rb of your app add this

config.api_only = false
Deliquesce answered 30/5, 2015 at 8:19 Comment(0)
G
3

Please include ActionDispatch::Flash middleware into your config/application.rb file.

config.middleware.use ActionDispatch::Flash

This may help you.

Goerke answered 27/10, 2015 at 11:58 Comment(0)
R
-2

The flash[:notice] will only appear after a redirect_to or a render (although you will need flash.now[:notice]).

The flash is there to provide feedback to the user on the status of an action that is taken by the user. Just rendering an index typically does not fall into this category as it is only displaying data, not showing the result of a user taking an action.

As an example:

def create
  @post = Post.new(params[:post])

  respond_to do |format|
    if @post.save
      format.html  { redirect_to(@post,
                    :notice => 'Post was successfully created.') }
    else
      format.html  { render :action => "new" }
    end
  end
end

In this case the flash will appear on the Post Show view only if the post has been saved directly.

Risinger answered 17/1, 2012 at 11:51 Comment(2)
I tried all I find in google, but still have NoMethodError in DashboardsController#index undefined method 'flash' for #<ActionDispatch::Request:0x7fee9329a9d0>Sulphurous
The question asks about flash method being undefined, not whether or not it appears. Even if there is no output from flash[:notice] calling flash should not result in NoMethodError under normal circumstances.Blaine

© 2022 - 2024 — McMap. All rights reserved.