views:

65

answers:

5

what would happen if both actions have some template to render?

+3  A: 

Yes you can, if it is in the same controller.

Calling zoo will provide the template for zoo with instances for @x and @a. Neither foo or bar will be rendered. If you have explicitly set a render method, then you might get a double render error, unless you return before the second render is called.

def foo
  @x = 1
end

def bar
  @a = 2
end

def zoo
  foo
  bar
end
The Who
if I explicitly set a render method in 'bar', then when 'zoo' is called, will it render bar's template (i.e. bar.html.erb) ?
Bat
Yes, but you will need to `return bar` in `zoo`, otherwise you will get a DoubleRender error.You are probably better abstracting the shared logic between `bar` and `zoo` into a protected method.
The Who
Thanks a lot, buddy!
Bat
A: 

You can use redirect_to to call another action within your controller. To render one template inside another, you can use partials and/or layouts.

Gabriel Ščerbák
`redirect_to` doesn't call the other action (in the sense of method calling), it instead tells the browser to request the other action. Actions are just methods, which are called by `ActionController` when it's handling a request. They can be called from other actions as @TheWho shows.
Tim Snowhite
A: 

The Who is correct about how to call the actions, but if you are calling an action within an action you need to refactor your code to pull out the logic that does what you are trying to accomplish into its own action, then allowing each action to render its own template.

Rabbott
A: 

Hi Bat

Yes you can do this. And if you might probably make a one layout nil so that it will display in your views in a nice way

say (this following example has the 'my_controller' as the layout)

class my_controller < application_controller 

   def my_parent_method
     @text_from_my_child_method = child_method
   end 

   def child_method
     return 'hello from child_method'
     render :layout => false #here we are making the child_method layout false so that it #will not effect the parent method
   end

end

and in your 'my_parent_method.rhtml' (view) you can use the variable

<%= @text_from_my_child_method %> and it should print 'hello from child_method'

hope this helps

cheers, sameera

sameera207
The `render` will never be called in `child_method`. You're `return`ing out of the method before the `render` line is executed. Are you trying to show that the `child_method` won't render a view? (That could be made concrete by declaring `child_method` as `private`.)
Tim Snowhite
A: 

If you want to do it because there's some sort of common code in both actions maybe it's better to refactor this code into a before_filter.

Francisco