간단하고 효율적인 방법은 counter_cache를 boss_location/discovered_location 관계에 추가하는 것입니다.
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은 계속됩니다 : 당신이 조인하지 않고 쿼리와 같은 결과를 얻을 수있는 방법은 :
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
당신은 가입 경로와 싶어 스틱, 당신은 이런 식으로 뭔가를해야 할 것입니다 경우 select의 count()는 모든 레코드를 포함하지만 원하는 상태 플래그를 제공합니다. 다행히 그게 당신이 찾고있는 것입니다.