开发者

Rails before_filter check multiple roles

In my before filter, I call a method containing the following code:

authorized_for_roles :administrator

In my application_controller

def authorized_for_roles(*roles)
roles.each{|role_name| return true if current_user.role.name == role_name}

This does not seem to be returning true even when logged in with the administrator role. Is my syntax incorrect?

If I switch the code to just read

return true if current_user.is_an_administrator?

everything works great. Can someone tell me how to modify the code to check is_an? for each role passed to the method? I'd like to be able to do something like

开发者_高级运维authorized_for_roles :administrator, :moderator

I tried

roles.each{|role_name|return true if current_user.try(:is_an, role_name)}

but this did not work.

EDIT: changed line spacing so that code snippets are formatted as such...


You want to use the Enumerable#any? method. In your first example:

def authorized_for_roles (*roles)
  roles.any? { |role_name| current_user.role.name == role_name }
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜