undefined method `flash' for #<ActionDispatch::Request

丶灬走出姿态 提交于 2020-01-04 03:52:09

问题


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.


回答1:


In config/applications.rb of your app add this

config.api_only = false



回答2:


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

config.middleware.use ActionDispatch::Flash

This may help you.




回答3:


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.



来源:https://stackoverflow.com/questions/8855060/undefined-method-flash-for-actiondispatchrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!