Ruby / Rails - Can I use a joined table's scope(or class method) as part of my WHERE clause?

后端 未结 1 407
盖世英雄少女心
盖世英雄少女心 2021-02-07 04:04

I want to grab all the categories that contain purchaseable products.

class Product < ActiveRecord::Base
  belongs_to :category
  scope :purchase         


        
1条回答
  •  心在旅途
    2021-02-07 04:49

    You should use the merge method

    class Category < ActiveRecord::Base
      has_many :products
      scope :with_purchaseable_products, joins(:products).merge(Product.purchaseable).group(:id).having('count(products.id) > 0')
    end
    

    Read more on http://asciicasts.com/episodes/215-advanced-queries-in-rails-3

    0 讨论(0)
提交回复
热议问题