Rails 4 scopes with has_many :through relations

Given the following Rails 4 model:

class Producer < ActiveRecord::Base has_many :producer_types has_many :types, :through => :producer_types
end

There are a couple ways you could create a scope on this model to retrieve only producers of a certain type.

First:

  scope :manufacturer, -> { where(:types => {:name => 'manufacturer'}).joins(:types) }

Second, to generate a dynamic scope for the given column name, you can take advantage of the following active record functionality:

  scope :with_type_name, lambda {|type_name|
    where(:types => {:name => type_name}).joins(:types)
  }