Rails通过关系查询has_many

Rails通过关系查询has_many

问题描述:

我的模型中有一个has_many关系,我在编写查询时遇到了麻烦。类别有四种模特属性(男装,女装,T恤和连帽衫),每种都有产品。我想要做的是找到一种方法来查询属于特定类别的所有产品(例如所有男士产品),然后将结果用于循环以在我的视图中显示产品数据。Rails通过关系查询has_many

我的模型结构如下。

感谢您的帮助!

我的产品型号

class Product < ActiveRecord::Base 
has_many :options, dependent: :destroy 
has_many :images, dependent: :destroy 

has_many :categorizations 
has_many :categories, through: :categorizations 

def image_url 
    self.images.first.url 
end 

def has_image? 
    self.images.exists? 
end 

end 

我的分类模型

class Category < ActiveRecord::Base 
has_many :categorizations 
has_many :products, through: :categorizations 
end 

我的分类已模型

class Categorization < ActiveRecord::Base 
belongs_to :category 
belongs_to :product 
end 

要遍历每个类别的产品:

Category.all.each do |category| 
    category.products.each do |product| 
    puts product 
    end 
end 

或找到一个类别,并通过它的产品循环:

category = Category.find(2) 
category.products.each do |product| 
    puts product 
end