2011-03-19 64 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()会给你你想要的状态标志。希望这就是你要找的。