In Rails 3, the ability to set flash parameters
:notice
and :alert
in a controllerredirect_to
call was added. Along with this change,ActionController::Base#notice
andActionController::Base#alert
were added as convenience accessors, which mapped to flash[:notice]
and flash[:alert]
respectively.
To set a custom flash type in your controller, you would have add the key/value pair to the controller
flash
hash, or you could also pass a hash to the optional :flash
option in redirect_to
.
As of Rails 4, developers will have the ability to register their own flash types by using the new
ActionController::Flash.add_flash_types
macro style method.The Rails 3 Way
Here is an example of setting a custom error flash type in Rails 3:
# app/controllers/users_controller.rb class UsersController < ApplicationController def create ... flash[:error] = "An error message for the user" redirect_to home_path end end # app/views/home/index <%= flash[:error] %>
The Rails 4 Way
Here is the same example as above, using Rails 4:
# app/controllers/application_controller.rb class ApplicationController ... add_flash_types :error, :another_custom_type end # app/controllers/users_controller.rb class UsersController < ApplicationController def create ... redirect_to home_path, error: "An error message for the user" end end # app/views/home/index <%= error %>
No comments:
Post a Comment