Rails 4:如何合并循环
问题描述:
我想知道如何在rails中合并循环。Rails 4:如何合并循环
我是否需要在控制器中执行该操作,或者甚至可以在视图中执行该操作?
如果我想知道如何决定渲染哪个部分。
例如,我必须建立模型:item
和receipe
。
首先,我如何将所有食谱和项目合并到一个循环中?
其次,如果我想渲染每个receipe
部分_receipe
和每个item
部分_item
,我该怎么做呢?
在此先感谢您的帮助!
答
这应该工作开箱:
# in the controller
items = Item.all # some scope on Items
receipes = Receipe.all # some scope on Receipes
@things = items + receipes # combine them into one variable
# in the view
render @things # renders a collection and renders for each item in
# the array a partial named like the item's class name