Rails: Pass parameters with render :action?

neezer picture neezer · Oct 10, 2009 · Viewed 37.3k times · Source

I have a form that displays differently depending on the parameter it was called with.

Ex.

testsite.local/users/new?type=client

So if type was a or b, the form would display different fields.

My problem is when the form is filled out incorrectly, because if the user couldn't be saved corrently, it renders the form with the default error messages, but also without my parameter.

testsite.local/users/new

How can I call my render action and pass whatever this parameter is set to to it? So that I can still keep my built-in error messages about why the form couldn't be sumbitted properly AND have it be the right form?

Here's my create action:

def create
   @user = User.new(params[:user])
   roles = params[:user][:assigned_roles]
   if @user.save
     update_user_roles(@user,roles)
     if current_user.is_admin_or_root?
       flash[:message] = "User \"#{@user.username}\" created."
       redirect_to users_path
     else
       flash[:message] = "Congrats! You're now registered!"
       redirect_to app_path
     end
   else
     render :action => 'new'
   end
 end

Answer

neezer picture neezer · Oct 12, 2009

As elucidated by another user answering my other related question, here's what I was after:

form_for @user, :url => { :action => :create, :type => @type }

... which preserves the parameter :type through each new render action (assuming I have it defined correctly in my controller).