Rails has_and_belongs_to_many 二级关联
Rails has_and_belongs_to_many on 2 level association
这与之前的问题有关
我在产品和供应商之间设置了 has_and_belongs_to_many。
在我看来我使用:
<td><%= product.suppliers.map {|supplier| supplier.NAME }.join(', ') %></td>
在我的 table.
中显示每行每行以逗号分隔的供应商列表
我现在需要在发票索引视图中显示相同的列表。 Invoices table 有一个 PRODUCT 列。我已经在 Invoice 模型上设置了 belongs_to :product。
我在发票索引视图中试过:
<td><%= invoice.product.suppliers.map {|supplier| product.supplier.NAME }.join(', ') %></td>
但是 returns
error undefined local variable or method `product'
为什么不起作用?我该如何解决?提前致谢。
你建错了.map
,试试
invoice.product.suppliers.pluck(:NAME).join(', ')
顺便说一句
在视图中使用逻辑是不好的做法,您应该将逻辑移至模型,并在视图中使用类似的东西:
<%= invoice.suppliers_names %>
应该return# => 'Name_1, Name_2, etc'
这与之前的问题有关
我在产品和供应商之间设置了 has_and_belongs_to_many。
在我看来我使用:
<td><%= product.suppliers.map {|supplier| supplier.NAME }.join(', ') %></td>
在我的 table.
中显示每行每行以逗号分隔的供应商列表我现在需要在发票索引视图中显示相同的列表。 Invoices table 有一个 PRODUCT 列。我已经在 Invoice 模型上设置了 belongs_to :product。
我在发票索引视图中试过:
<td><%= invoice.product.suppliers.map {|supplier| product.supplier.NAME }.join(', ') %></td>
但是 returns
error undefined local variable or method `product'
为什么不起作用?我该如何解决?提前致谢。
你建错了.map
,试试
invoice.product.suppliers.pluck(:NAME).join(', ')
顺便说一句
在视图中使用逻辑是不好的做法,您应该将逻辑移至模型,并在视图中使用类似的东西:
<%= invoice.suppliers_names %>
应该return# => 'Name_1, Name_2, etc'