Finding records with two specific records in another table

前端 未结 3 1991
再見小時候
再見小時候 2021-02-09 13:19

I have a Product model that has_and_belongs_to_many :taxons, and I want to find all products that are in specific taxons.

For example, if a pro

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-09 14:14

    I had this problem a while back, thankfully there is a nice solution.

    def self.has_taxons(taxons)
      id = arel_table[:id]
      Product.joins(:taxons).where(taxons: { name: taxons }).group(id).having(id.count.eq(taxons.size))
    end
    

提交回复
热议问题