aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJon Leighton <j@jonathanleighton.com>2012-01-31 08:50:36 +0000
committerJon Leighton <j@jonathanleighton.com>2012-01-31 08:50:36 +0000
commitb2955edcea63e3daa347dc4e05b9abd380176ac8 (patch)
treee97e7dc4ca132e4b289d32c2f6d5f38112a2295e
parent0bfc504d9ced49d50afa7a8b19680ae7f42c2b24 (diff)
downloadrails-b2955edcea63e3daa347dc4e05b9abd380176ac8.tar.gz
rails-b2955edcea63e3daa347dc4e05b9abd380176ac8.tar.bz2
rails-b2955edcea63e3daa347dc4e05b9abd380176ac8.zip
Allow writing unknown attributes, but with a deprecation warning. Closes #4583.
-rw-r--r--activerecord/lib/active_record/attribute_methods/write.rb11
-rw-r--r--activerecord/test/cases/attribute_methods_test.rb7
2 files changed, 14 insertions, 4 deletions
diff --git a/activerecord/lib/active_record/attribute_methods/write.rb b/activerecord/lib/active_record/attribute_methods/write.rb
index fde55b95da..8c6fa90a28 100644
--- a/activerecord/lib/active_record/attribute_methods/write.rb
+++ b/activerecord/lib/active_record/attribute_methods/write.rb
@@ -28,11 +28,14 @@ module ActiveRecord
@attributes_cache.delete(attr_name)
column = column_for_attribute(attr_name)
- if column || @attributes.has_key?(attr_name)
- @attributes[attr_name] = type_cast_attribute_for_write(column, value)
- else
- raise ActiveModel::MissingAttributeError, "can't write unknown attribute `#{attr_name}'"
+ unless column || @attributes.has_key?(attr_name)
+ ActiveSupport::Deprecation.warn(
+ "You're trying to create an attribute `#{attr_name}'. Writing arbitrary " \
+ "attributes on a model is deprecated. Please just use `attr_writer` etc."
+ )
end
+
+ @attributes[attr_name] = type_cast_attribute_for_write(column, value)
end
alias_method :raw_write_attribute, :write_attribute
diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb
index fb53eb1a4b..cdff7ef017 100644
--- a/activerecord/test/cases/attribute_methods_test.rb
+++ b/activerecord/test/cases/attribute_methods_test.rb
@@ -780,6 +780,13 @@ class AttributeMethodsTest < ActiveRecord::TestCase
assert_deprecated { klass.define_attribute_methods }
end
+ def test_setting_new_attributes_deprecated
+ t = Topic.new
+ assert_deprecated { t[:foo] = "bar" }
+ assert_equal "bar", t.foo
+ assert_equal "bar", t[:foo]
+ end
+
private
def cached_columns
@cached_columns ||= time_related_columns_on_topic.map(&:name)