2011-03-19 65 views
1

嘿有, 我有一個用戶模型,一個discovered_locations模型和一個boss_locations模型。Rails 3加入問題

boss_location是老闆位置的靜態表示。發現的位置是(user_id,boss_location_id)。

什麼是一個不錯的方法(如果我猜想涉及範圍更好),以獲得用戶老闆位置和發現位置的連接?

也就是說,我想獲得老闆地點的加入。我想要所有的老闆地點,無論是否發現,但我想知道他們是否被發現。

你會怎麼做?

回答

2

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