Rails 4集合局部渲染

3

我显然在做错了什么,但我不明白它。

我有一个部分调用,如下所示:

= render 'shared/purchase', collection: @purchases

@purchases在控制器中被定义如下:

@purchases = current_user.purchases

但是我遇到了这个错误:
app/views/shared/_purchase.html.slim where line #3 raised:

undefined local variable or method `purchase' for #<<Class:0x007fd8ca54f970>:0x007fd8ca54eb60>

然而,当我将局部更改为仅呈现local_assigns时,我看到了这个:
[:collection, #<ActiveRecord::Associations::CollectionProxy [#<Purchase id: 40, user_id: 20, purchaseable_id: 6, purchaseable_type: "PurchaseType", frequency: "Weekly", day: "Su", notes: "leave at gate", allergies: "peanuts", created_at: "2013-07-24 16:58:08", updated_at: "2013-07-24 16:58:08", size: "Normal", quantity: 2>, #<Purchase id: 41, user_id: 20, purchaseable_id: 5, purchaseable_type: "PurchaseType", frequency: "Weekly", day: "Su", notes: "leave at gate", allergies: "peanuts", created_at: "2013-07-24 16:58:08", updated_at: "2013-07-24 16:58:08", size: "Jumbo", quantity: 3>, #<Purchase id: 42, user_id: 20, purchaseable_id: 7, purchaseable_type: "PurchaseType", frequency: "Weekly", day: "Su", notes: "leave at gate", allergies: "peanuts", created_at: "2013-07-24 16:58:08", updated_at: "2013-07-24 16:58:08", size: nil, quantity: 1>, #<Purchase id: 43, user_id: 20, purchaseable_id: 8, purchaseable_type: "PurchaseType", frequency: "Weekly", day: "Su", notes: "leave at gate", allergies: "peanuts", created_at: "2013-07-24 16:58:08", updated_at: "2013-07-24 16:58:08", size: nil, quantity: 1>]>]
[:purchase, nil]

为什么每个集合项没有被作为本地变量purchase捕获?

我很困惑,我确信这是一个愚蠢的问题。我之前多次做过类似的事情,甚至将旧的工作代码与这个进行比较,但我无法弄清楚问题出在哪里。要么这是一个新的Rails 4功能,在文档中我没有看到,要么我就是个笨蛋。

谢谢!


2
Rails文档提供了一个使用renderpartial参数的示例(<%= render partial: "product", collection: @products %>)。我不确定这是否会有所不同,但值得一试。 - Kyle Decot
@KyleDecot 是的,完全正确。多么愚蠢的错误啊。如果你回答了,我会给你功劳。 - goddamnyouryan
2
一点也不傻。我也会期望它能够正常工作。 - Kyle Decot
1
刚刚花了太多时间与这个问题纠结!谢谢Kyle Decot! - danielricecodes
哈哈,一样的问题 - 这让我感到很烦恼,因为我认为我已经完全按照文档操作了。 - DavidM
1个回答

10
Rails文档中关于Rails中的布局和渲染的内容,使用了render函数的partial参数举例说明:Layouts and Rendering in Rails
<h1>Products</h1>
<%= render partial: "product", collection: @products %>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接