When an action in a controller has been called, can I then call another action from that action?
And what wo开发者_运维技巧uld happen if both actions have some template to render?
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
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.
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.
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.
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
精彩评论