2009-12-08 48 views
1

它必須是一個非常普遍的問題。我有這樣一個鏈接許多一對多的關係:N N鏈接has_many通過:用戶 - >角色 - >列表。查找用戶分配到的列表(通過角色)

用戶n的< ==>ň角色< ==>列表

ActiveRecord的模式:

class User 
    # linking to roles 
    has_many :role_assignments 
    has_many :roles, :through => :role_assignments 
end 

class Role 
    # linking back to users 
    has_many :role_assignments 
    has_many :users, :through => :role_assignments 

    # linking to lists 
    has_many :list_assignments 
    has_many :lists, :through => :list_assignments 
end 

class List 
    # linking back to roles 
    has_many :list_assignments 
    has_many :roles, :through => :list_assignments 
end 

# ... and the join models: 
class RoleAssignment 
    belongs_to :role 
    belongs_to :user 
end 

class ListAssignment 
    belongs_to :list 
    belongs_to :role 
end 

會是一個什麼named_scope或List模型中的關聯來查找所有具有所有角色的列表,這些角色又有一個特定的用戶?

任何提示將不勝感激!

+0

哪裏role_assignments和list_assignments模式?您需要連接表上的belongs_to聲明。 – bensie 2009-12-08 19:37:47

+0

爲了簡潔,我省略了這些,但是您的問題讓我覺得我應該添加它們。 – mxgrn 2009-12-08 19:58:52

回答

0

我能想出迄今最好的解決辦法是:

class List 
    has_many :list_assignments 
    has_many :roles, :through => :list_assignments 

    named_scope :managable_by_user, lambda { |u| 
    role_ids = u.roles.map(&:id) 
    { 
     :include => [:list_assignments], 
     :conditions => {:list_assignments => {:role_id => role_ids}} 
    } 
    } 
end 
相關問題