Reputation: 21
I have three tables, one of which is a many-to-many relationship table:
class Category < ApplicationRecord
has_many :categorizations
has_many :products, :through => :categorizations
end
class Product < ApplicationRecord
has_many :categorizations, dependent: :destroy
has_many :categories, :through => :categorizations
end
and the table Categorizations:
class Categorization < ApplicationRecord
belongs_to :category
belongs_to :product
end
I saved the categories ids in a array:
def product_params
params.require(:product).permit(:name_product, :hallmark, :description, :image_url, :price, category_ids:[])
end
In new.html.erb:
<% Category.all.each do |category| %>
<label>
<%= check_box_tag "product[category_ids][]", category.id, field.object.categories.include?(Category) %>
<%= category.name_category %>
</label>
<%end%>
I can't display the category names. In show.html.erb I tried everything, but it only displays the ID of the categories in which the product belongs.
How do I display the category names? In the database I can do a JOIN
, but in Ruby on Rails it is difficult.
Upvotes: 2
Views: 255
Reputation: 2860
It does not able in Rails to store a relation in an array column. You may load necessary categories
and make access by category id
.
# for single product
category_ids = product.category_ids
# for many products
category_ids = products.flat_map(&:category_ids)
# load categories
categories = Category.where(id: category_ids).index_by(&:id)
# the result structure
# {1 => #<Category id: 1, ...>, 2 => #<Category id: 2, ...> ... }
# now all related categories preloaded
products.each do |product|
product.category_ids.each do |category_id|
puts categories[category_id]
end
end
Upvotes: 0