简体   繁体   中英

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.

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. I have already set belongs_to :product on Invoice model.

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

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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