鉴于以下模型:
class User < AR::B
has_many :permissions
has_many :projects, :through => :permissions
end
class Project < AR::B
has_many :permissions
has_many :users, :through => :permissions
end
class Role < AR::B
has_many :permissions
end
class Permission < AR::B
belongs_to :user
belongs_to :project
belongs_to :role
end
在user.rb模型中,我如何获得用户对项目的许可?
喜欢的东西 self.permissions.role?
谢谢!
答案 0 :(得分:2)
您可以向User模型添加一个实例方法,该方法将项目作为参数并返回权限。
class User < AR
def permission_for_project(project)
permissions.find_by_project_id(project.id)
end
def role_for_project(project)
permission = permissions.find_by_project_id(project.id)
permission.role unless permission.nil?
end
end
然后使用它:
user = User.find(n)
project = Project.find(n)
permission = user.permission_for_project(project)
role = user.role_for_project(project)
答案 1 :(得分:1)
(the_role = user.permissions.find(:first, project_id => project_id).role) &&
the_role.name
应该查找用户对该项目的(第一个)权限并获得该角色。如果有一个角色,那么它将返回该名称,否则它将返回nil。