一个简单而有效的方法是将一个counter_cache添加到boss_location/discovered_location关系中。你可以查询,而不加入,并得到了相同的结果这样:
class BossLocation < ActiveRecord::Base
has_many :discovered_locations
scope :discovered, where(["#{quoted_table_name}.discovered_locations_count > ?", 0])
scope :undiscovered, where(["#{quoted_table_name}.discovered_locations_count = ?", 0])
def discovered?
self.discovered_locations_count > 0
end
end
class DiscoveredLocation < ActiveRecord::Base
belongs_to :user
belongs_to :boss_location, :counter_cache => true
end
如果你想坚持与加盟路线,你必须做这样的事情:
class BossLocation < ActiveRecord::Base
has_many :discovered_locations
scope :with_discovery_status, joins("LEFT OUTER JOIN discovered_locations ON boss_locations.id = discovered_locations.boss_location_id").group("boss_locations.id").select("boss_locations.*, count(discovered_locations.id) AS discover_status")
def discovered?
self[:discover_status].present? && self['discover_status'].to_i > 0 || self.discovered_locations.size > 0
end
end
的LOJ将继续所有的记录,但选择count()会给你你想要的状态标志。希望这就是你要找的。