Skip to content

Instantly share code, notes, and snippets.

@mariovisic
Created July 13, 2012 01:43
Show Gist options
  • Save mariovisic/3102220 to your computer and use it in GitHub Desktop.
Save mariovisic/3102220 to your computer and use it in GitHub Desktop.
Mass assignment with roles
class Admin < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation, :remember_me, :name
attr_accessible :role, :as => :administrator
end
# These 3 all work as expected:
Admin.new(:name => 'foo') #=> #<Admin ... >
Admin.new({:role => 'master of the universe'}, :as => :administrator) #=> #<Admin ... >
Admin.new(:role => 'sheep hoarder') #=> Can't mass-assign protected attributes: role
# This one does not work and I don't want to duplicate the first attr_accessible line for administrator users.
Admin.new({:name => 'Bob', :role => 'donkey kong'}, :as => :administrator) #=> Can't mass-assign protected attributes: name
@robzolkos
Copy link

I think you'll need to use

attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :role, :as => :administrator

Sucks.

@mariovisic
Copy link
Author

Managed to fix it by updating the model:

class Admin < ActiveRecord::Base
  attr_accessible :email, :password, :password_confirmation, :remember_me,
    :name, :as => [ :default, :administrator ]
  attr_accessible :role, :as => :administrator
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment