简体   繁体   English

Rails has_and_belongs_to_many在2级关联

[英]Rails has_and_belongs_to_many on 2 level association

This is related to this previously asked question 这与先前提出的问题有关

I have a has_and_belongs_to_many in place between Product and Supplier. 我在产品和供应商之间有一个has_and_belongs_to_many。

In my view I use: 我认为我使用:

<td><%= product.suppliers.map {|supplier| supplier.NAME }.join(', ') %></td>

To show list of suppliers comma separated on each row for each product in my table. 为了显示供应商列表,在我的表格中每行的每行用逗号分隔。

I now need to show the same list on invoices index view. 现在,我需要在发票索引视图上显示相同的列表。 Invoices table has a column PRODUCT. 发票表中的PRODUCT列。 I have already set belongs_to :product on Invoice model. 我已经在发票模型上设置了Emirates_to:product。

I tried in my invoices index view: 我在发票索引视图中尝试过:

<td><%= invoice.product.suppliers.map {|supplier| product.supplier.NAME }.join(', ') %></td>

but it returns 但它返回

error undefined local variable or method `product' 错误未定义的局部变量或方法“产品”

Why isn't that working? 为什么这样不起作用? How can I fix it? 我该如何解决? Thanks in advance. 提前致谢。

you build wrong .map , try 您建立了错误的.map ,请尝试

invoice.product.suppliers.pluck(:NAME).join(', ')

BTW BTW

it's bad practice use logic in view, you should move your logic to models, and in view use something like: 在视图中使用逻辑是不好的做法,您应该将逻辑移到模型中,并在视图中使用类似以下内容的方法:

<%= invoice.suppliers_names %>

what should return # => 'Name_1, Name_2, etc' 什么应该返回# => 'Name_1, Name_2, etc'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM