标准/管理员用户的before_action:如何为管理员提供所有其他用户的权限?

时间:2015-07-09 07:25:15

标签: ruby-on-rails railstutorial.org

我想为我的管理员用户提供一些普通用户的权利,这里是我的before_action:

# users_controller.rb
before_action :correct_user, only: [:edit, :update, :show]
before_action :admin_user, only: [:destroy, :index, :admin_toggle]

因此,如果您是正确的用户,则可以:编辑,更新,显示您自己的个人资料。

如果你是admin_user,你可以看到列表(索引),销毁你自己的个人资料,切换管理员任何用户,编辑/更新/显示你自己的个人资料(admin_user也是一个correct_user)。

我希望admin_user能够编辑,更新,显示其他成员的个人资料:我是否需要编写特定的方法,或者是否有使用before_action的技巧?

似乎admin_user应该拥有correct_user的权限 - 给出任何用户ID - 。

1 个答案:

答案 0 :(得分:1)

如果你使用某些特定的身份验证工具,例如Devise。然后我建议实施授权解决方案 cancancan宝石。您在models目录下有一个特定的能力文件,您可以在其中声明不同用户角色的访问权限。

使您的未来代码更清晰,更易于阅读。

###编辑:

正如之前的回答指出的那样,还有一个CanCan宝石,但据我所知,它在Rails4中是not supported。在写这个答案的时候,github中的CanCanCan build-status被标记为failing,但我现在已经在我的项目中使用了很长时间了,我很高兴:)

<强> ###

ability.rb示例:

def secretary_abilities
  can [:create, :read, :update], Person
end

def superadmin_abilities
  # superadmin can do everything that secretary can
  secretary_abilities
  # ...and can also do destructive actions
  can [:destroy], Person
end

之后,您可以将检查添加到您的视图中,如下所示:

<% if can? :show, Person %>
  <%= link_to 'Show', person_path(@person) %>
<% end %>