开发者

How to have two 'access levels' on a model in Rails?

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

开发者_如何学C
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?

  1. 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 in Admin::UsersController, like

    @user.admin = params[:user][:admin]
    
  2. I can scrub the parameter in the UsersController, which is even worse

    params[: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?


how about subclassing? maybe try something like this:

class User < ActiveRecord::Base
    attr_accessible :columns, :that, :are, :safe, :for, :users
end

class AdminUser < User
    attr_accessible :admin
end

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.


Consider reworking your resources to look something like:

users/guest
users/user
users/admin

where

admin<user 

and

user<guest

Building on Jon's excellent answer, you could try something like the following:

class Guest < ActiveRecord::Base
  attr_accessible :columns, :that, :are, :safe, :for, :guests
  attr_reader :is_admin
end

class User < Guest
  attr_accessible :more, :stuff, :for, :users
end

class AdminUser < User
  attr_accessible :some, :adminThings, :here
  attr_writer :is_admin
end

... and then AdminUser will inherit attr_read for :is_admin from Guest.

Hope that helps -

Perry


Looks like Rails 3.1 will have exactly what I wanted.

http://ablogaboutcode.com/2011/05/12/activerecord-3-1-mass-assignment-roles/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜