2010-04-16 61 views
0
class User < ActiveRecord::Base 
    has_many :memberships 
    has_many :groups, :through => :memberships 

class Group < ActiveRecord::Base 
    has_many :memberships 
    has_many :users, :through => :memberships 

    def moderators 
    # relationship_id is in the memberships table 
    self.users.find(:all, :conditions => ['relationship_id = ?', 1]) 
    end 
end 

鑑於上述代碼,這是實現moderators方法的最佳方法嗎?我的目標是能夠在給定組中找到具有「主持人」關係的所有用戶。現在,我可以使用的方法來遍歷實例方法,named_scope或關聯擴展

# ... 
@group.moderators 

我認爲一個協會擴展,它是有道理的用在這裏,因爲我要求對符合條件的用戶的一個子集的所有主持人。但語法似乎多餘的要求是主持人的用戶

# Association extension - seems redundant 
@group.users.moderators 

我認爲是一個named_scope,但我無法弄清楚如何實現它沒有錯誤。即使我能夠將named_scope返回到所有組中的所有主持人,這些都不是我想要的。

# named_scope: returns all the moderators across all the groups 
moderators = Group.moderators 

我想知道什麼在這裏最好的做法是,爲什麼我會想我們的關聯擴展(或named_scope)在實例方法因爲它允許一個更簡潔的語法?

回答

1

在組類添加關聯:

class Group < ActiveRecord::Base 
    has_many :memberships 
    has_many :users, :through => :memberships 

    has_many :moderators, :source => :user, :through => :memberships, 
       :conditions => ['relationship_id = ?', 1] 
end 

現在,你可以做到以下幾點:

@group.moderators 
@group.moderators.size 
@group.moderators.find_by_city(..) 
+0

完美!我在AWDWR上閱讀過它,並沒有意識到這一點。感謝聚光燈。在功能上做這個和使用實例方法完全一樣,還是增加一個條件關聯還有其他好處嗎? – caspyin 2010-04-16 17:30:00

+0

它們與實例方法不同。您可以鏈接在User類上定義的關聯方法和named_scope。 – 2010-04-16 18:21:36