我有三个表,其中一个表是多对多关系表:
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
和表分类:
class Categorization < ApplicationRecord
belongs_to :category
belongs_to :product
end
我将类别ID保存在数组中:
def product_params
params.require(:product).permit(:name_product, :hallmark, :description, :image_url, :price, category_ids:[])
end
在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%>
我无法显示类别名称。在show.html.erb中我尝试了所有内容,但它只显示产品所属类别的ID。
如何显示类别名称?在数据库中我可以做JOIN
,但在Ruby on Rails中很难。
答案 0 :(得分:0)
在Rails中无法在数组列中存储关系。您可以加载必要的categories
并通过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