I am an experienced PHP developer but new to RoR and trying to understand how every thing works. I know how to use flash hash i.e in my action method, I'll set
flash[:notice] = 'some message'
and in my view, i'll display that.
This mechanism is also implemented in Yii framework. I understand how it works there. The thing that I don't understand is how it actually works here in RoR. flash
is just a local variable then how can I access it in my views?
Flash messages are notifications and alerts that pop up in the interface of an application in order to communicate with the user and ease of interaction. Applications often apply flash messages to tell the user if the login was correct or to confirm the success of the action triggered by clicking a button.
A flash message is a way to communicate information with the users of your Rails application so they can know what happens as a result of their actions. Example messages: “Password changed correctly” (confirmation) “User not found” (error)
In order to implement flash in your own apps, there's a specific set of steps that must be taken. You first call and set flash in your action controller. You must tell flash precisely what you want it to persist forward. Redirect your action controller to the full-page reload of your choice.
flash
is actually a method. It's not in your controller, but the Rails controller delegates it to the request object. So the flash
method is defined in the request object, but you can access it from your controllers, and from the view.
Check the link to the ActionDispatch::Request
code. The flash is actually stored inside the session when set. The next time the user requests a page, the flash is accessible for use in the views.
In your view you can just access it like this:
<%= flash[:notice] %>
Or in a aesthetically more pleasant way (this can only be done with notice and alert since they're so frequently used):
<%= flash.notice %>
See the documentation for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With