如何使用连接表

问题描述:

我有三个表,其中之一是许多一对多的关系表显示元素的列表:如何使用连接表

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 

def product_params 
    params.require(:product).permit(:name_product, :hallmark, :description, :image_url, :price, category_ids:[]) 
    end 

在new.html.erb:

我一个阵列中已保存的类别的ID

<% 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

什么是部门?你的'new.html.erb'代码与问题中其余的信息无关。 – infiniteRefactor

+1

“在数据库中,我可以加入......”。是的,这可能是正确的做法。当DBM能够完成筛选和处理工作时,您希望避免移动大量数据,并让Ruby或Rails完成繁重的工作。我已经看到需要花费数秒钟才能完成数据移动的任务,而在Ruby中处理的任务需要亚秒级时间才能让DBM进行搜索,筛选和紧缩,然后仅返回所需的记录。这可以减少应用程序或Web服务器上的网络负载和CPU负载。 –

它不能在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