Rails 3 merging scopes with joins
rails-activerecord, ruby-on-rails
Solution
Apparently, at this time you can only merge simple constructs that don't involve joins. Here is a possible workaround if you modify your models to look like this:
class SolarSystem < ActiveRecord::Base
has_many :planets
has_many :planet_types, :through => :planets
scope :has_earthlike_planet, joins(:planet_types).merge(PlanetType.like_earth)
end
class Planet < ActiveRecord::Base
belongs_to :solar_system
belongs_to :planet_type
scope :like_earth, joins(:planet_type).merge(PlanetType.like_earth)
end
class PlanetType < ActiveRecord::Base
has_many :planets
attr_accessible :gravity, :life
scope :like_earth, where(:life => true, :gravity => 9.8)
end
** UPDATE **
For the record, a bug was filed about this behavior - hopefully will be fixed soon...
Problem
Setup For this question, I'll use the following three classes: ``` class SolarSystem < ActiveRecord::Base has_many :planets scope :has_earthlike_planet, joins(:planets).merge(Planet.like_earth) end class Planet < ActiveRecord::Base belongs_to :solar_system belongs_to :planet_type scope :like_earth, joins(:planet_type).where(:planet_types => {:life => true, :gravity => 9.8}) end class PlanetType < ActiveRecord::Base has_many :planets attr_accessible :gravity, :life end ``` Problem The scope `has_earthlike_planet` does not work. It gives me the following error: ActiveRecord::ConfigurationError: Association named 'planet_type' was not found; perhaps you misspelled it? Question I have found out that this is because it is equivalent to the following: ``` joins(:planets, :planet_type)... ``` and SolarSystem does not have a `planet_type` association. I'd like to use the `like_earth` scope on `Planet`, the `has_earthlike_planet` on `SolarSystem`, and would like to avoid duplicating code and conditions. Is there a way to merge these scopes like I'm attempting to do but am missing a piece? If not, what other techniques can I use to accomplish these goals?