2011-03-19 12 views
1

안녕하세요, 나는 사용자 모델, discover_locations 모델 및 boss_locations 모델이 있습니다.레일 3 가입 질문

boss_location은 보스 위치의 정적 표현입니다. 발견 된 위치는 (user_id, boss_location_id)입니다.

사용자 상사 위치와 발견 된 위치의 조인을 얻는 좋은 방법은 무엇입니까 (범위가 맞습니까?

즉, 보스 위치에 가입하고 싶습니다. 나는 모든 보스 위치를 발견하거나 찾지 않기를 원하지만 발견 된 것인지 알고 싶다.

어떻게 하시겠습니까?

답변

2

간단하고 효율적인 방법은 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()는 모든 레코드를 포함하지만 원하는 상태 플래그를 제공합니다. 다행히 그게 당신이 찾고있는 것입니다.