【问题标题】:Rails - how to get all manufactures from a product category?Rails - 如何从产品类别中获取所有制造商?
【发布时间】:2012-08-06 09:15:44
【问题描述】:

我有Category 模型,放置产品。每个产品都属于制造商(也有没有设置制造商的产品——这些我想标记为“未知”)。

这是我的模型:

class Product < ActiveRecord::Base
  belongs_to :manufacturer
  belongs_to :category
end

class Manufacturer < ActiveRecord::Base
  has_many :products
end

class Category < ActiveRecord::Base
  has_ancestry
  has_many :products
end

这是一个简单的查询,我如何从各个类别中获取产品:

@products = @category.products.paginate(:page => params[:page], :per_page => 15)

我想打印所有制造商,在相应类别中有产品...我在这部分苦苦挣扎了半天,仍然找不到查询...

你能帮我做这部分吗?

谢谢!

【问题讨论】:

    标签: sql ruby-on-rails ruby activerecord join


    【解决方案1】:

    将此添加到您的类别模型中:

    has_many :manufacturers, :through => :products
    

    然后就可以调用了

    @category.manufacturers
    

    查看has_many 的文档以了解有关through 选项的更多信息。

    【讨论】:

      【解决方案2】:

      你可以试试这个:

      Manufacturer.where(id: @category.products.map(&:manufacturer_id).uniq)
      

      或者我们可以依靠数据库来获取唯一值,这在大表上应该更快:

      Manufacturer.where(id: Product.select("DISTINCT manufacturer_id").
        where(category: @category).map(&:manufacturer_id))
      

      我们可以通过在 rails >= 3.2.1 中使用 pluck 方法来简化这一点:

      Manufacturer.where(id: Product.uniq.where(category_id: @category.id).
        pluck(:manufacturer_id))
      

      我还想补充一点,has_many :manufacturers, :through =&gt; :products 解决方案在大数据上可能会因为加入而慢一些(根据我的经验)。

      【讨论】:

      • 谢谢!只是尝试集成,但我面临这个问题:undefined method "where" for #&lt;Array:0x00000142973bd0&gt;。我错过了什么吗?
      • 对不起,请用最后一个再试一次。
      • 谢谢,我试过了,我得到了PG::Error: ERROR: column products.category does not exist,而不是上面的错误。但是category_id 列存在于products 表中
      • 抱歉,我手头没有那个新数据库。现在它应该可以工作了。
      猜你喜欢
      • 2021-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多