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.

iwasrobbed
  • 46,496
  • 21
  • 150
  • 195
user1148210
  • 57
  • 1
  • 5
  • Are you inheriting from `ApplicationController` which is inheriting from `ActionController::Base`? For example, does your controller look like: `class DashboardsController < ApplicationController` at the top? – iwasrobbed Jan 13 '12 at 20:14
  • 3
    Are you using the `rails-api` gem by chance? – sethvargo Aug 31 '12 at 16:29
  • For anyone who is using `rails-api`, see [here](http://stackoverflow.com/a/21149689/21115) – davetapley Feb 02 '15 at 17:39

3 Answers3

3

In config/applications.rb of your app add this

config.api_only = false
Sharvil
  • 129
  • 12
3

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

config.middleware.use ActionDispatch::Flash

This may help you.

Amol Udage
  • 2,917
  • 19
  • 27
-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.

nmott
  • 9,454
  • 3
  • 45
  • 34
  • I tried all I find in google, but still have `NoMethodError in DashboardsController#index undefined method 'flash' for #` – user1148210 May 16 '12 at 16:40
  • 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. – Sammy Larbi Nov 21 '14 at 22:48