【发布时间】:2011-08-29 20:09:56
【问题描述】:
在我的前置过滤器中,我调用了一个包含以下代码的方法:
authorized_for_roles :administrator
在我的application_controller
def authorized_for_roles(*roles)
roles.each{|role_name| return true if current_user.role.name == role_name}
即使以管理员角色登录,这似乎也不会返回 true。我的语法不正确吗?
如果我将代码切换为只读
return true if current_user.is_an_administrator?
一切都很好。有人可以告诉我如何修改代码以检查 is_an 吗?对于传递给方法的每个角色?我希望能够做类似的事情
authorized_for_roles :administrator, :moderator
我试过了
roles.each{|role_name|return true if current_user.try(:is_an, role_name)}
但这不起作用。
编辑:更改了行距,以便代码 sn-ps 被格式化...
【问题讨论】:
-
你在使用 gem 来做角色吗? is_an_administrator 是什么?定义?
-
我从 Ernie Miller 那里得到的 - [link]metautonomo.us/2008/09/30/easy-role-based-authorization
codedef method_missing(method_id, args) if match = matches_dynamic_role_check?(method_id) tokenize_roles(match.captures.first) .每个都做|检查|如果 role.name.downcase == check end 返回 false 否则 super end end private def matches_dynamic_role_check?(method_id) /^is_an?_([a-zA-Z]\w)\?$/. match(method_id.to_s) end def tokenize_roles(string_to_split) string_to_split.split(/_or_/) end
标签: ruby-on-rails authorization roles before-filter