Archive

Posts Tagged ‘render action’

render :action and passing parameters

November 9, 2009 Leave a comment

in rails, I think most of you have come across with render action (Ex: render :action => “index” etc..). And have you ever wanted to render an action which expect some parameters ?!. OK.. Let me be clear, I have following controller actions

 

def new

@project = Project.find(params[:project_id])

end

— here my new action is expecting a parameter called project_id to load a project. And in down deep in my controller I have a create method. There I’m going to save a user object for a given project.  I want it to save with out a problem and if so it will redirect to root url and if not it should render the new action again (with error messages).

 

def create

if @user.save

#if user object successfully saved then redirect

redirect_to root_url

else

#but if saving failed then redirect beck to new action.

render :action => ‘index’,  :params => { :project_id => <project id> }

end

end

But this render action fails. Problem is even though we pass the parameters rails actually dont run the action method again (http://dev.rubyonrails.org/ticket/11037), so your parameters will not be used anyware.

Is there any alternative ?

Yes, there are many, and one would be loading the required objects before render the action again. So as per my example it should adjust like,

 

def create

if @user.save

#if user object successfully saved then redirect

redirect_to root_url

else

#lets load the project object before rendering the action

@project = Project.find(<project id>)

render :action => ‘index’

end

end

 

this would do the trick ,  Hope this helps..  🙂

 

 

 

 

 

 

 

 

 

Advertisements
Categories: Ruby Rails Tags: