Reputation: 3289
I have a Product
model and a Tag
model in a has_and_belongs_to_many
relationship with a join_table
. My Tag has one string column called name
.
Everything works, but on my Product index view, I'd like to list all the Tags associated with the Product. Since its in a join_table, I am not sure how to create the bridge to get the Tag name; all I seem to be able to do is list all the tag_ids.
products/index.html.erb
<% @products.each do |product| %>
<tr>
<td><%= product.name %></td>
<td><%= product.tag_ids %></td>
...
</tr>
<% end %>
tag.rb
class Tag < ApplicationRecord
has_and_belongs_to_many :products
...
end
product.rb
class Product < ApplicationRecord
...
has_and_belongs_to_many :tags
...
end
Upvotes: 0
Views: 56
Reputation: 2384
Tags should be accessible throug product.
You could simply call tags
on your product
instance if I got issue correctly.
<% product.tags.map do |tag| %>
...
<%= tag.name %>
...
<% end %>
Upvotes: 4