Created
May 16, 2011 13:39
-
-
Save dpickett/974447 to your computer and use it in GitHub Desktop.
scoped mass assignment overview
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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