views:

26

answers:

2

Say I have controllers Apples and Bees, and new actions in both. In Bee's new action, I set some variables for display in 'bees/new'. I happen to also want to render this same template from Apples's new method. What's the correct way of setting up the variables in this case? I take it copying over the assignments from Bees isn't the right way of going about it.

A: 

If you're going to be displaying it in more than one place, your best bet is to use a partial. You can move all relevant view code into a partial (let's call it "apples_new", which means you'd save it as /app/views/apples/_apples_new.html.erb).

Then, in your regular apples/new.html.erb view you can just call that partial:

<!-- /app/views/apples/new.html.erb -->
<h1>Apples New</h1>
<%= render :partial => "apples_new" %>

And in your Bees "new" view, you can do:

<!-- /app/views/bees/new.html.erb -->
<h1>Bees New</h1>
<% if @bees.has_apples? $>
  <%= render :partial => "apples/apples_new" %>
<% end %>

Note that in my example above, I'm adding some logic. I'm assuming you only want to call the same form in certain scenarios, so I added the "has_apples?" method to demonstrate the logic.

Mike Trpcic
A: 

Quick note: you can also compress that logic into one line:

<%= render :partial => "apples/apples_new" if @bees.has_apples? %>

jeffpatt