Bat
Bat

Reputation: 133

Can I call an action in another action (in a rails controller)?

When an action in a controller has been called, can I then call another action from that action?

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

Upvotes: 13

Views: 15861

Answers (5)

The Who
The Who

Reputation: 6622

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

Upvotes: 23

sameera207
sameera207

Reputation: 16619

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

Upvotes: -1

Fran
Fran

Reputation: 1073

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.

Upvotes: -1

Rabbott
Rabbott

Reputation: 4332

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.

Upvotes: 0

Gabriel Ščerb&#225;k
Gabriel Ščerb&#225;k

Reputation: 18560

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.

Upvotes: 0

Related Questions