开发者

Rendering view from different controller

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 copyi开发者_JS百科ng over the assignments from Bees isn't the right way of going about it.


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.


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

"apples/apples_new" if @bees.has_apples? %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜