链接has_many通过:用户 - >角色 - >名单。查找分配给用户的列表(通过角色)

时间:2009-12-08 18:48:16

标签: ruby-on-rails activerecord many-to-many

这一定是一个非常普遍的问题。我有这样一个链接的多对多关系:

用户n< ==> n角色n< ==> 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或关联是什么,以查找具有所有角色的所有列表,而这些列表又具有特定用户?

任何提示都将不胜感激!

1 个答案:

答案 0 :(得分: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