Question

I've rolled out my own authentication/authorization system based on Hartl's for my app. I wanted to allow admins to make other users admins, so I did this in my user.rb file:

attr_accessible :name, :email, :password, :password_confirmation, :order_id
attr_accessible :name, :email, :password, :password_confirmation, :order_id, :admin, :as => :administrator

and put this in my user update action:

def update
   if current_user.admin?
      if @user.update_attributes(params[:user], :as => :administrator)

This works great for me, but it's getting annoying to have to go into console and type

User.find(2).toggle!(:admin)

or whatever, whenever I want to make my first admin user after a db reset, or, for that matter, to have to use the console or individual edits to make other admins. I'd love it if I could seed ":as => administrator", so I tried this in my seed.rb file, but it doesn't work (mass-assign error):

    admin = User.create(
    :name => "My Name",
    :email => "my email",
    :password => "password",
    :password_confirmation => "password",
    :admin => true,
    :as => :administrator
)

Any idea if there's a way to do this? It'd make my life a lot easier.

Était-ce utile?

La solution

The simplest solution I found was to toggle admin in the seeds.rb file right after creating the user. This way, I avoid "mass" assignment without having to assign in the console. So:

admin = User.create(
    :name => "My Name",
    :email => "my email",
    :password => "password",
    :password_confirmation => "password"
)
admin.toggle!(:admin)
# I assume "admin.update_attribute(:admin, true)" would work as well.

Autres conseils

Since you have a mass-assign error, I think you should only keep the second line of attr_accessible in User.rb and discard the first line, which is causing the error.

I was looking to perform the same thing and end up doing like this in seeds.rb:

# db/seeds.rb
users = User.create({email: 'email@admin.com', username: 'admin', password: 'sEcReT', password_confirmation: 'sEcReT', role: 'admin'},
                    :as => :admin)

# models/user.rb
attr_accessible :email, :username, :password, :password_confirmation, :role, :as => :admin
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top