This feature is schedule for: Rails v2.3 stable
Rails’ flash is a convenient way of passing objects (though mostly used for message strings) across http redirects. In fact, every time you set a flash parameter the very next step is often to perform your redirect w/ redirect_to:
1 2 3 4 5 6 7 |
class UsersController < ApplicationController def create @user = User.create(params[:user]) flash[:notice] = "The user was successfully created" redirect_to user_path(@user) end end |
I know I hate to see two lines of code where one makes sense – in this case what you’re saying is to “redirect to the new user page with the given notice message” – something that seems to make more sense as a singular command.
DHH seems to agree and has added :notice, :alert and :flash options to redirect_to to consolidate commands. :notice and :alert automatically sets the flash parameters of the same name and :flash let’s you get as specific as you want. For instance, to rewrite the above example:
1 2 3 4 5 6 |
class UsersController < ApplicationController def create @user = User.create(params[:user]) redirect_to user_path(@user), :notice =>"The user was successfully created" end end |
Or to set a non :alert/:notice flash:
1 2 3 4 5 6 |
class UsersController < ApplicationController def create @user = User.create(params[:user]) redirect_to user_path(@user), :flash => { :info => "The user was successfully created" } end end |
I’ve become accustomed to setting my flash messages in :error, :info and sometimes :notice making the choice to provide only :alert and :notice accessors fell somewhat constrained to me, but maybe I’m loopy in my choice of flash param names.
Whatever your naming scheme, enjoy the new one-line redirect!
tags: ruby, rubyonrails
