diff options
author | Josh Kalderimis <josh.kalderimis@gmail.com> | 2011-04-23 15:00:24 +0200 |
---|---|---|
committer | Josh Kalderimis <josh.kalderimis@gmail.com> | 2011-04-24 09:53:18 +0200 |
commit | a08d04bedfd01cc0a517ccedf74f2ceac70eb28d (patch) | |
tree | 4179b4383b3afd37d843573ac996d6a3acb5bf87 /activerecord/lib/active_record | |
parent | 1054ebd613c5596bc1ebb8d610d19e5fa374cca5 (diff) | |
download | rails-a08d04bedfd01cc0a517ccedf74f2ceac70eb28d.tar.gz rails-a08d04bedfd01cc0a517ccedf74f2ceac70eb28d.tar.bz2 rails-a08d04bedfd01cc0a517ccedf74f2ceac70eb28d.zip |
Added assign_attributes to Active Record which accepts a mass-assignment security scope using the :as option, while also allowing mass-assignment security to be bypassed using :with_protected
Diffstat (limited to 'activerecord/lib/active_record')
-rw-r--r-- | activerecord/lib/active_record/base.rb | 41 |
1 files changed, 40 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 9a01d793f9..4512e8c8ad 100644 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -1640,10 +1640,49 @@ end # user.is_admin? # => true def attributes=(new_attributes, guard_protected_attributes = true) return unless new_attributes.is_a?(Hash) + if guard_protected_attributes + assign_attributes(new_attributes) + else + assign_attributes(new_attributes, :without_protection => true) + end + end + + # Allows you to set all the attributes for a particular mass-assignment + # security scope by passing in a hash of attributes with keys matching + # the attribute names (which again matches the column names) and the scope + # name using the :as option. + # + # To bypass mass-assignment security you can use the :without_protection => true + # option. + # + # class User < ActiveRecord::Base + # attr_accessible :name + # attr_accessible :name, :is_admin, :as => :admin + # end + # + # user = User.new + # user.assign_attributes({ :name => 'Josh', :is_admin => true }) + # user.name # => "Josh" + # user.is_admin? # => false + # + # user = User.new + # user.assign_attributes({ :name => 'Josh', :is_admin => true }, :as => :admin) + # user.name # => "Josh" + # user.is_admin? # => true + # + # user = User.new + # user.assign_attributes({ :name => 'Josh', :is_admin => true }, :without_protection => true) + # user.name # => "Josh" + # user.is_admin? # => true + def assign_attributes(new_attributes, options = {}) attributes = new_attributes.stringify_keys + scope = options[:as] || :default multi_parameter_attributes = [] - attributes = sanitize_for_mass_assignment(attributes) if guard_protected_attributes + + unless options[:without_protection] + attributes = sanitize_for_mass_assignment(attributes, scope) + end attributes.each do |k, v| if k.include?("(") |