如何拥有两个“访问级别”在 Rails 中的模型上?
让我们假设一个简单且常见的场景。
我有一个带有 admin
字段的 User
模型。用户无法编辑其 admin
字段,但管理员可以编辑任何人的 admin
字段。
因此,我需要为这两种类型的用户提供适当的访问权限。
如果我以 RESTful 方式呈现此内容,我将拥有两个资源,比如说
resource :user
namespace :admin do
resources :users
end
......这里出现了困境 - 如何控制 admin
字段的哪些位置可以更改,哪些位置不可以更改?
我可以设置
attr_protected :admin
以防止用户更改其管理员状态。但随后我必须在Admin::UsersController
中对其进行特殊处理,例如@user.admin = params[:user][:admin]
我可以在
UsersController
中擦除参数,这甚至是更糟params[:user].delete(:admin)
这两种解决方案对我来说看起来都很混乱。处理此类情况的正确方法是什么?
如果访问级别超过 2 个怎么办?
Let's assume a simple and common scenario.
I have a User
model with an admin
field. Users cannot edit their admin
field, but admins can edit anyone's admin
field.
So, I need to give both types of users appropriate access.
If I'd present this in a RESTful way, I'd have two resources, say
resource :user
namespace :admin do
resources :users
end
...And here comes the dilemma - how do I control where the admin
field can be changed and where not?
I can set
attr_protected :admin
to prevent users from changing their admin status. But then I'd have to make a special case out of it inAdmin::UsersController
, like@user.admin = params[:user][:admin]
I can scrub the parameter in the
UsersController
, which is even worseparams[:user].delete(:admin)
Both of these solutions look messy to me. What's the correct way of dealing with such situations?
What if there's more than 2 access levels?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
子类化怎么样?也许尝试这样的事情:
然后在每个控制器中使用适当的模型。请注意,在 User 类中使用 attr_protected 在这种情况下不起作用,因为 AR(当前)无法智能地应用它们,它会抱怨 :admin 只能在其中之一。无论如何,使用 attr_accessible 通常是更好的做法。
how about subclassing? maybe try something like this:
then use the appropriate model in each controller. note using attr_protected in the User class won't work in this scenario since AR doesn't (currently) intelligently apply them, it will complain that :admin can only be in one. using attr_accessible is generally better practice anyway though.
考虑重新设计您的资源,使其看起来像这样:
在
Jon 的出色答案的基础上
,您可以尝试类似以下内容:
... 然后 AdminUser 将从 Guest 继承 attr_read for :is_admin 。
希望有帮助 -
佩里
Consider reworking your resources to look something like:
where
and
Building on Jon's excellent answer, you could try something like the following:
... and then AdminUser will inherit attr_read for :is_admin from Guest.
Hope that helps -
Perry
看来 Rails 3.1 正是我想要的。
http://ablogaboutcode.com/2011/05/ 12/activerecord-3-1-质量分配-角色/
Looks like Rails 3.1 will have exactly what I wanted.
http://ablogaboutcode.com/2011/05/12/activerecord-3-1-mass-assignment-roles/