Tuesday, July 24, 2007

Rails: Calling another action

It is interesting how Rails behaves when one action calls another as part of processing a request.

Here is my test:

app/controllers/test_controller.rb
def action1
@foo = "action1"
end

def action2
@foo = "action2"
end

app/view/test/action1.rhtml
<h1>action1.rhtml</h1>
<h2><%= @foo %></h2>

app/view/test/action2.rhtml
<h1>action2.rhtml</h1>
<h2><%= @foo %></h2>

Here is what I observed when I call action2 from action1 like so:

def action1
@foo = "action1"
action2
end

def action2
@foo = "action1"
end

  • If none of the actions have a render explicitly defined, then calling action2 from action1 will simply execute the logic defined in the action2 method. The template that will be rendered will be action1.rhtml
  • If both of the actions have a render explictly defined, then calling action2 from action1 is a multi-render error. It doesn't matter if you use render :template or render :action or just render.
  • If only action2 has an explicit render defined, then
    - action2 method is executed
    - if action2 calls a default template render, then action1.rhtml will be used as the template
    - if action2 calls a specific template, say render :action => 'action2', then action2.rhtml is used.
    Note that it is a multi-render error in this case if action1 also has an explicit render defined in it.

1 comment:

Anonymous said...

This helped me. Thank you!