我正在构建一个最终将在代码级别使用cancan的授权框架。我正在创建模型和关联,并且几乎完美无缺,但我遇到了障碍。
我有多个连接表(user_roles和role_rights)的用户,角色和权限,我有设置的东西,以便你可以做User.roles和User.roles.first.rights但我希望能够做User.rights
class User < ActiveRecord::Base
has_many :user_roles
has_many :roles, :through => :user_roles
end
class UserRole < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
class Role < ActiveRecord::Base
has_many :user_roles
has_many :users, :through => :users_roles
has_many :role_rights
has_many :rights, :through => :role_rights
end
class RoleRight < ActiveRecord::Base
belongs_to :role
belongs_to :right
end
class Right < ActiveRecord::Base
has_many :role_rights
has_many :roles, :through => :role_rights
end
以下作品:
User.roles
这样做:
User.roles.first.rights
但我想做的是:
User.rights
但是当我尝试时,我得到以下错误:NoMethodError:undefined method`reight'
我认为我需要在User模型中添加一些内容,让它横向于Right模型,但我无法弄清楚这些关联。
我正在使用Rails 2.3.4和Ruby 1.8.7
答案 0 :(得分:1)
尝试这样的事情:
class User < ActiveRecord::Base
def self.rights
Right.joins(:roles => :user).all("users.id = ?", self.id)
end
end