【问题标题】:Rails querying a has_many through relationshipRails 通过关系查询 has_many
【发布时间】: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


    【解决方案1】:

    循环浏览每个类别的产品:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-12
      相关资源
      最近更新 更多