2

Disclaimer: I'm using Rails 3.2. Specifically, in the Rails 3 in Action book:

The User model does have attr_accessible attr_accessible :email, :password, password_confirmation, :remember_me

The User model NOT have :admin listed, therefore it can't be mass-assigned to as part of params[:user].


The form_for block inside app/views/admin/users/_form.html.erb sets up a checkbox element to allow an admin to set a user as an admin:

` <%= f.check_box :admin %> <%= f.label :admin, "Is an admin?" %>


The app/controllers/admin/users_controller.rb

@user = User.new(params[:user])
@user.admin = params[:user][:admin] == "1"  
if @user.save

The line @user.admin = params[:user][:admin] == "1" should set the admin attribute to true, but generates mass-assignment errors which prevent me from changing the @user.admin attribute to true.


I can set the admin attribute to true without mass-assigning via the console, along with defining a method in the User model:

def make_admin
  self.admin = true
end

This accomplishes the same thing, nothing fancy.

How do I get the admin attribute assigned to TRUE for the user to work using a view & controller via the checkbox?

Is there a way to remove or separate the admin parameter from params[:user][:admin])?

Joe C
  • 1,223
  • 1
  • 10
  • 23

2 Answers2

2

Commenting out the config.active_record.mass_assignment_sanitizer = :strict line in the development.rb file moved me forward.

Joe C
  • 1,223
  • 1
  • 10
  • 23
1

It's a bad idea to comment the mass assignement protection.

Why don't you add :admin to the list of attr_accessible if you want it to be mass assigned ?

And for information, when you type this :

@user = User.new(params[:user])
@user.admin = params[:user][:admin] == "1"  
if @user.save

It's not the @user.admin = ... which throw a mass assignment error, but the line User.new(params[:user])

Anyway, if you want to retrieve the value of the checkbox, but don't want to mass-assign it, try this :

admin = params[:user].delete(:admin)
@user = User.new(params[:user])
@user.admin = admin == "1"  
if @user.save

Don't forget to re-enable the mass assignment protection ;)

Byscripts
  • 2,549
  • 1
  • 15
  • 25