I'm building a simple blog-style application. I really only need admin and non-admin users, so it seems like having a simple column in the user model called admin (boolean) will suffice.

I'm using Devise for authorization right now, and I've got the admin column added. I'm trying to set up my default admin user (myself) in seeds.rb, however admin comes out as false unless I add the admin column to attr_accessible. It seems like this would be a security concern, however, and I don't generally want admin users to be able to be created except by another admin. What's the correct, and safe, way to do this?

有帮助吗?

解决方案

You are very correct to leave admin as not attr_accessible, this just disables setting it via mass-assignment. You can still set admin in your seeds by setting it singularly. Example:

user = User.new(:name => 'joe') ...
user.admin = true
user.save

其他提示

You want to handle setting the admin boolean internally. Don't expose it to mass-assignment.

Have your user model automatically default the first user (you) to an admin. Use a before_create method for this...

# models/user.rb
before_create :make_first_user_an_admin

def make_first_user_an_admin
  self.admin = self.class.count == 0 # sets true if no users exist, false otherwise
end

Then use an instance method to set adminship...

# models/user.rb
def toggle_admin
  self.admin = !self.admin
  save
end

guard this method in your controller...

# controllers/users_controller.rb
def change_adminship
  if current_user.admin
    @user.toggle_admin
  else
    raise "Can't do that."
  end
end
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top