Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering Partials From One Controller’s View to Another Controller’s View in Rails

I have a view for a controller called "show". Inside that view, i want to render the contents of another controller's view - and obviously, the logic for the form on that view to talk to the controller it belongs too. How do I do this? I am fairly new to rails and I'm not 100% confident with the framework yet.

You could almost consider them "widgets" on the view. I know you can render actions from the same controller on the view by using:

render :action => "show_home_page", :layout=> false

but I need it to render the action (view) from another controller.

ie.

I have a view, which is rendered onto a layout. That view, belongs to controller A. I need to render the "index" and "new" views from controller B inside the original view (above)

.

like image 692
Ash Avatar asked Nov 20 '09 02:11

Ash


1 Answers

The terminology in your question is a little confused. If are in a controller and you want to execute the code in another action method in another controller and render its template, you should redirect_to that action. Let's say the other controller is called ContractsController

redirect_to :controller => "contracts", :action => "show_home_page"

If you just want to use the view template from another method as the response from your action, you just need to prefix the name of the controller in the render parameter. This will not call the action, it will just use its template.

For example, if the template lives in the folder for the contracts controller.

render :action => "/contracts/show_home_page", :layout=> false

I think in this case you are actually talking about a partial, which would look like

render :partial => "/contracts/show_home_page"

However, what I see you grasping at here is that you actually want to call multiple action methods to render a single page. This is not how it works. You are going to have to set up the objects that the templates will reference in a single action. This is one reason most Rails developers put a lot of code in the models, so the setup isn't repeated all over the controllers.

But there is another way... where the magic of JavaScript comes in.

In your page, create a function like this:

<script type="text/javascript" language="javascript">    
function load_categories() {
            <%= remote_function(:url => {:controller => "categories", :action => "list"},
                                  :update => "categories")%>
        };
</script>

If you call that in the onload even of your page, it will replace the div with id "categories" with the response from the action referenced.

like image 127
MattMcKnight Avatar answered Oct 04 '22 14:10

MattMcKnight