[英]Rails querying a has_many through relationship
我的模型中具有has_many通过关系,并且在编写查询时遇到问题。 类别具有四个模型属性(男人,女人,T恤和帽衫),每个属性中都包含商品。 我想做的是找到一种查询属于特定类别的所有产品(例如所有男装产品),然后在循环中使用该结果在我的视图中显示产品数据的方法。
我的模型结构如下。
谢谢您的帮助!
我的产品型号
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.