The problem is that some things are obvious and others simply seem obvious. Recently i was trying to alter a controller’s create action. By default if creation of the model fails the following code is executed:
render :action => ‘new’
The extra functionality i wanted was to pass the parameter :id into the above action. So i wrote this:
render :action => ‘new’, :id => myvalue
The problem to the above is that params[:id] didn’t get myvalue. After noumerous attempts and no luck searching the internet i came up with the solution.
params[:id] = myvalue
render :action => ‘new’
Trying to rationalize why the above code worked, i came to the conclusion that what ‘render’ does is simply to render the new.rhtml file and not execute the ‘new’ action from scratch. So the code contained in new.rhtml is executed in the context of the ‘create’ method of your controller. It is reasonable then to initialize params[:id] in ‘create’ method and then use its value in new.rhtml.
If the above reasoning is false in any way let me know.
By for now and keep coding. 🙂
Thanks kmak!
You’re right – ‘render’ just renders the template for the action specified rather than executes the action code.
yes. another way to get around the problem if you need to execute the action prior to the view:
new
render :action :new
the first statement executes the action and then the render statement throws out the view.
i understand that u can call the action method first and then render it corresponding view. but, wont calling the action method itself render the view automatically?
After nany testing i figured that when you call an action from within another action it doesn’t render it’s view.
You have to call render :action => ‘blabla’ to render it.
A better way to do it is
render_component :controller => “your_controller”, :action => ‘new’, :params => {:id => ‘myvalue’}
but the :id param always has to stand alone
http://dev-journal.3dmdesign.com/rails-application-development/passing-id-when-rendering-a-component
you can even save it to a string like so
@data render_component_as_string :controller => βyour_controllerβ, :action => βnewβ, :params => {:id => βmyvalueβ}