使用 cancan 获取未定义的局部变量或方法“roles”;
我已经放弃尝试锁定应用程序中的每个操作。目前,我正在放置除设计/注册之外的每个控制器:
load_and_authorize_resource
在用户模型中:
def role?(role)
roles.include? role.to_s
end
在能力模型中:
if user.role? :superadmin
can :manage, :all
end
但是,我收到以下错误:
undefined local variable or method `roles'
app/models/user.rb:33:in `role?'
app/models/ability.rb:7:in `initialize'
感谢您的帮助。
更新:由于 Bohdan 下面的回答,我进一步查看了文档,发现设置 cancan 模型有不同的方法。目前我们有 6 个不同的角色,导致数据库中有 6 个不同的布尔字段。我正在考虑一种分层方法来定义角色,其中一个用户可以拥有多个角色,一个角色可以拥有多个用户。有两种方法可以设置角色定义。 首先。 第二。为了便于使用,我想我将详尽地定义每个角色,这样每个人只有一个角色。想知道这样做的缺点是什么。
更新:我注释掉了除上面定义的超级管理员之外的所有其他角色。意识到这与多对多问题没有任何关系。所以...?
I've given up on trying to lock down every action in the application. Currently I'm placing in every controller except the devise/registration:
load_and_authorize_resource
in the user model:
def role?(role)
roles.include? role.to_s
end
in the ability model:
if user.role? :superadmin
can :manage, :all
end
However, I am getting the following error:
undefined local variable or method `roles'
app/models/user.rb:33:in `role?'
app/models/ability.rb:7:in `initialize'
Thanks for your help.
UPDATE: Because of Bohdan's answer below i looked further into the documentation and found there are differing methods of setting up the cancan model(s). currently we have 6 different roles resulting in 6 different Boolean fields in the database. I was thinking of a hierarchical approach to defining roles where one user could have many roles and one role has many users. There are two ways to set up the role definitions. First. Second. For ease of use i think i'll define each role exhaustively so there is only one role for each person. Wondering what the disadvantages of that are.
UPDATE: I commented out all the other roles other than superadmin as defined above. Realized that it doesn't have anything to do with many to many issue. So...?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的模型或方法
roles
的任何其他自定义定义中应该有has_and_belongs_to_many
:roles 编辑
在添加
has_and_belongs_to_many :roles 到您的
User
模型,以使您需要的一切正常工作定义名为
Role
的新模型,至少更改
name
属性要编辑
迁移,
只需添加此迁移并运行
rake db:migrate
rails将完成剩下的工作You should have
has_and_belongs_to_many :roles
in your model or any other custom definition for methodroles
Edit
after you added
has_and_belongs_to_many :roles
to yourUser
model to make everything work you needdefine new model called
Role
with at leastname
attributechange
to
Edit
migration
just add this migration and run
rake db:migrate
rails will do the restRails HBTM 关系按字母顺序对表名称进行排序。尝试将您的迁移更改为
rails HBTM relations order the table name alphabetically. Try changing your migration to