【发布时间】:2014-09-12 21:30:24
【问题描述】:
我的模型中有一个 has_many through 关系,我在编写查询时遇到了问题。类别有四个模型属性(男装、女装、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
【问题讨论】:
标签: ruby-on-rails ruby activerecord