class Property < ActiveRecord::Base
has_many :units
def self.default_scope
where('active_at <= :now AND inactive_at > :now', now: Time.zone.now)
end
end
class Unit < ActiveRecord::Base
belongs_to :property
def self.with_active_properties
joins(:property)
end
end
I'm trying to use Rails 4.0.2 default_scope with a join, but when I call Unit.with_active_properties
Why do I get the following duplicated SQL?
SELECT "units".* FROM "units" INNER JOIN "properties" ON "properties"."id" = "units"."property_id" AND (active_at <= '2014-03-11 03:36:13.994068' AND inactive_at > '2014-03-11 03:36:13.994068') AND (active_at <= '2014-03-11 03:36:13.967550' AND inactive_at > '2014-03-11 03:36:13.967550')
After further investigation, it appears that this error is the result of a bug in rails 4.0.x that leads to the the default_scope being called twice. I posted the problem on github here:
https://github.com/rails/rails/issues/14351
Credit needs to go out to Larry Reid for his fantastic help with this problem.