[英]How can I clear out the Rails flash object after responding to an Ajax request?
I am doing this type of thing for some of my controller actions:我正在为我的一些控制器操作做这种类型的事情:
def my_method
flash[:notice] = "Success."
respond_to do |format|
format.js { render 'common/flashes' }
end
end
And it works great, and the flash alerts and notices show up fine.它工作得很好,闪光警报和通知显示正常。 But when the user clicks to go to another page, the flash messages show up one more time.但是当用户点击进入另一个页面时,闪现信息又出现一次。 Rails apparently doesn't know that they were used because of the way I'm handling them.由于我处理它们的方式,Rails 显然不知道它们被使用过。 How do I clear them out after doing the render above?完成上面的渲染后如何清除它们?
Rahul's answer can be expressed more succinctly in application_controller.rb
or any other controller as: Rahul 的回答可以在application_controller.rb
或任何其他控制器中更简洁地表达为:
after_filter -> { flash.discard }, if: -> { request.xhr? }
This takes advantage of ActionController
's handling of lambdas and conditional filters.这利用了ActionController
对 lambdas 和条件过滤器的处理。
In your application_controller.rb在您的 application_controller.rb
after_filter :clear_xhr_flash
def clear_xhr_flash
if request.xhr?
# Also modify 'flash' to other attributes which you use in your common/flashes for js
flash.discard
end
end
Neither of these answers worked for me on rails 5.2.这些答案都不适用于 Rails 5.2。 After calling flash.discard
i still had a flash message.调用flash.discard
我仍然收到一条 Flash 消息。 Instead I had to call flash[:notice] = nil
相反,我不得不调用flash[:notice] = nil
For cleaning all flashes use flash.clear
instead of flash.discard
要清洁所有闪光灯,请使用flash.clear
而不是flash.discard
https://api.rubyonrails.org/v5.1.7/classes/ActionDispatch/Flash/FlashHash.html#method-i-clear https://api.rubyonrails.org/v5.1.7/classes/ActionDispatch/Flash/FlashHash.html#method-i-clear
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.