This post originated from an RSS feed registered with Ruby Buzz
by rwdaigle.
Original Post: What's New in Edge Rails: Set Flash in redirect_to
Feed Title: Ryan's Scraps
Feed URL: http://feeds.feedburner.com/RyansScraps
Feed Description: Ryan Daigle's various technically inclined rants along w/ the "What's new in Edge Rails" series.
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:
1234567
classUsersController < ApplicationControllerdefcreate@user = User.create(params[:user]) flash[:notice] = "The user was successfully created" redirect_to user_path(@user)endend
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:
123456
classUsersController < ApplicationControllerdefcreate@user = User.create(params[:user]) redirect_to user_path(@user), :notice =>"The user was successfully created"endend
Or to set a non :alert/:notice flash:
123456
classUsersController < ApplicationControllerdefcreate@user = User.create(params[:user]) redirect_to user_path(@user), :flash => { :info => "The user was successfully created" }endend
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!