diff --git a/activerecord/lib/active_record/attribute_assignment.rb b/activerecord/lib/active_record/attribute_assignment.rb index b36c90fc08..df4de8ac35 100644 --- a/activerecord/lib/active_record/attribute_assignment.rb +++ b/activerecord/lib/active_record/attribute_assignment.rb @@ -2,7 +2,7 @@ require 'active_support/concern' module ActiveRecord ActiveSupport.on_load(:active_record_config) do - mattr_accessor :whitelist_attributes, instance_accessor: false + mattr_accessor :whitelist_attributes, instance_accessor: false mattr_accessor :mass_assignment_sanitizer, instance_accessor: false end @@ -11,12 +11,12 @@ module ActiveRecord include ActiveModel::MassAssignmentSecurity included do - attr_accessible(nil) if Model.whitelist_attributes + initialize_mass_assignment_sanitizer end module ClassMethods def inherited(child) # :nodoc: - child.attr_accessible(nil) if Model.whitelist_attributes + child.send :initialize_mass_assignment_sanitizer if self == Base super end @@ -28,6 +28,11 @@ module ActiveRecord default << 'id' unless primary_key.eql? 'id' default end + + def initialize_mass_assignment_sanitizer + attr_accessible(nil) if Model.whitelist_attributes + self.mass_assignment_sanitizer = Model.mass_assignment_sanitizer if Model.mass_assignment_sanitizer + end end # Allows you to set all the attributes at once by passing in a hash with keys diff --git a/activerecord/test/cases/mass_assignment_security_test.rb b/activerecord/test/cases/mass_assignment_security_test.rb index c75a0be98e..73a01906b9 100644 --- a/activerecord/test/cases/mass_assignment_security_test.rb +++ b/activerecord/test/cases/mass_assignment_security_test.rb @@ -278,6 +278,38 @@ class MassAssignmentSecurityTest < ActiveRecord::TestCase ActiveRecord::Model.whitelist_attributes = prev end end + + test "ActiveRecord::Model.mass_assignment_sanitizer works for models which include Model" do + begin + sanitizer = Object.new + prev, ActiveRecord::Model.mass_assignment_sanitizer = ActiveRecord::Model.mass_assignment_sanitizer, sanitizer + + klass = Class.new { include ActiveRecord::Model } + assert_equal sanitizer, klass._mass_assignment_sanitizer + + ActiveRecord::Model.mass_assignment_sanitizer = nil + klass = Class.new { include ActiveRecord::Model } + assert_not_nil klass._mass_assignment_sanitizer + ensure + ActiveRecord::Model.mass_assignment_sanitizer = prev + end + end + + test "ActiveRecord::Model.mass_assignment_sanitizer works for models which inherit Base" do + begin + sanitizer = Object.new + prev, ActiveRecord::Model.mass_assignment_sanitizer = ActiveRecord::Model.mass_assignment_sanitizer, sanitizer + + klass = Class.new(ActiveRecord::Base) + assert_equal sanitizer, klass._mass_assignment_sanitizer + + sanitizer2 = Object.new + klass.mass_assignment_sanitizer = sanitizer2 + assert_equal sanitizer2, Class.new(klass)._mass_assignment_sanitizer + ensure + ActiveRecord::Model.mass_assignment_sanitizer = prev + end + end end