Permalink
Browse files

protecting attributes from mass assignment by default

  • Loading branch information...
1 parent e9c0c6f commit 145b77b070817e445591ad5b6b23aa37b7f6042a @ryanb committed Jun 1, 2009
@@ -2,6 +2,18 @@ module TrustedParams
module ActiveRecordAdditions
def self.included(base)
base.extend(ClassMethods)
+ base.attr_accessible nil
+ end
+
+ def remove_attributes_protected_from_mass_assignment(attributes)
+ unless self.class.accessible_attributes.include? "all"
+ attributes.each do |key, value|
+ unless self.class.accessible_attributes.include? key.to_s
+ raise ActiveRecord::UnavailableAttributeAssignmentError, "attribute \"#{key}\" is protected from mass assignment"
+ end
+ end
+ end
+ attributes
end
module ClassMethods
@@ -12,7 +24,12 @@ def attr_protected(*args)
end
end
-# TODO for some reason this doesn't work for overriding methods
-# ActiveRecord::Base.class_eval do
-# include TrustedParams::ActiveRecordAdditions
-# end
+module ActiveRecord
+ # TODO for some reason this doesn't work for overriding methods
+ # Base.class_eval do
+ # include TrustedParams::ActiveRecordAdditions
+ # end
+
+ class UnavailableAttributeAssignmentError < ActiveRecordError
+ end
+end
View
@@ -18,17 +18,15 @@ def self.paginate(options)
self.paginate_options = options
end
- def self.add_column(name, column_type = :string)
+ def self.add_column(name)
returning ActiveRecord::ConnectionAdapters::Column.new(name, nil) do |column|
- def column.type
- column_type
- end
@columns ||= []
@columns << column
end
end
def self.reset_columns
+ write_inheritable_attribute(:attr_accessible, [])
@columns = []
end
@@ -4,9 +4,27 @@
before(:each) do
MockedModel.reset_columns
MockedModel.add_column(:name)
+ MockedModel.add_column(:content)
end
it "should not allow one to set attr_protected" do
lambda { MockedModel.attr_protected(:foo) }.should raise_error
end
+
+ it "should not be able to mass assign attributes by default" do
+ lambda { MockedModel.new(:name => "foo") }.should raise_error(ActiveRecord::UnavailableAttributeAssignmentError)
+ end
+
+ it "should be able to mass assign any attribute with :all" do
+ MockedModel.attr_accessible :all
+ m = MockedModel.new(:name => "foo")
+ m.name.should == "foo"
+ end
+
+ it "should be able to mass assign specific attributes" do
+ MockedModel.attr_accessible :name
+ user = MockedModel.new(:name => "foo")
+ user.name.should == "foo"
+ lambda { MockedModel.new(:content => "foo") }.should raise_error(ActiveRecord::UnavailableAttributeAssignmentError)
+ end
end

0 comments on commit 145b77b

Please sign in to comment.