1
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

我正在尝试将 Rails 4.0.2 default_scope 与连接一起使用,但是当我调用时Unit.with_active_properties为什么会得到以下重复的 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')
4

1 回答 1

1

经过进一步调查,这个错误似乎是由于 rails 4.0.x 中的错误导致 default_scope 被调用两次。我在github上发布了这个问题:

https://github.com/rails/rails/issues/14351

信用需要感谢拉里·里德(Larry Reid)在这个问题上的出色帮助。

于 2014-03-13T00:40:51.647 回答