Skip to content

Instantly share code, notes, and snippets.

@dpickett
Created May 16, 2011 13:39
Show Gist options
  • Select an option

  • Save dpickett/974447 to your computer and use it in GitHub Desktop.

Select an option

Save dpickett/974447 to your computer and use it in GitHub Desktop.
scoped mass assignment overview
class User < ActiveRecord::Base
belongs_to :group
attr_accessible :name
end
user = User.new(:name => "John", :group_id => 5)
user.attributes # {:name => "John", :group_id => nil} group_id is nil because it is not accessible
class User < ActiveRecord::Base
belongs_to :group
attr_protected :group_id
end
user = User.new(:group_id => 5)
user.group_id # nil due to attribute protection
class User < ActiveRecord::Base
attr_accessible :name
attr_accessible :role, :as => :admin
end
#don't use a scope, so role is protected
#IE you'd use a normal scope for mass assignment in a users/update action
user = User.new(:name => "John", :role => "admin")
user.attributes # {:name => "John", :role => nil}
#now with the admin scope I can set the role
#IE you'd use an admin scope when in your administrative backend (/admin/users/update)
user = User.new({:name => "John", :role => "admin"}, :as => :admin)
user.attributes # {:name => "John", :role => "admin"}
secure_or_controlled_attributes = {:name => "John", :role => "admin"}
user = User.new(secure_or_controlled_attributes, :without_protection => true)
user.attributes # {:name => "John", :role => "admin") #role is not protected because of the without_protection argument
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment