Search code examples
ruby-on-rails-3joinfinder

Applying scopes in joins


I have following models:

class Category < ActiveRecord::Base
  has_many :items
  default_scope where(:enabled => true, :out_of_stock => false)
  scope :enabled, where(:enabled => true)
  scope :out_of_stock, where(:out_of_stock => true)
end

class Item < ActiveRecord:Base
  belongs_to :category
end

I've faced following code duplication, repeating scope conditions across entire project, when using joins:

Category.joins(:offers).where(:items => {:merchant_id => @merchant.id, :enabled => true, :out_of_stock => false})

It would be nice, if applying specified scope in joins will be possible:

Category.joins(:offers).where(:items => {:merchant_id => @merchant.id, :scope => :default})

Solution

  • Try using & like this:

    Category.joins(:offers, :items) & Item.default.where(:merchant_id => @merchant.id)
    

    I think this is called interpolation. It joins the two queries together, preserving the first one as the base (it return Category objects).