一個簡單而有效的方法是將一個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()會給你你想要的狀態標誌。希望這就是你要找的。