Ruby rails: How to render an action and pass parameters to it

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. 🙂

6 thoughts on “Ruby rails: How to render an action and pass parameters to it”

  1. Thanks kmak!

    You’re right – ‘render’ just renders the template for the action specified rather than executes the action code.

  2. 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.

  3. 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?

  4. 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.

  5. you can even save it to a string like so

    @data render_component_as_string :controller => β€œyour_controller”, :action => β€˜new’, :params => {:id => β€˜myvalue’}

Comments are closed.