Skip to content

Commit

Permalink
Allow writing unknown attributes, but with a deprecation warning. Closes
Browse files Browse the repository at this point in the history
  • Loading branch information
jonleighton committed Jan 31, 2012
1 parent 0bfc504 commit b2955ed
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
11 changes: 7 additions & 4 deletions activerecord/lib/active_record/attribute_methods/write.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,14 @@ def write_attribute(attr_name, value)
@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

Expand Down
7 changes: 7 additions & 0 deletions activerecord/test/cases/attribute_methods_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -780,6 +780,13 @@ def parent.inherited(k)
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)
Expand Down

0 comments on commit b2955ed

Please sign in to comment.