1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

update_columns raises if the column is unknown

Previosly, `update_columns` would just take whatever keys you gave it
and tried to run the update query. Most likely this would result in an
error from the database. However, if the column actually did exist, but
was in `ignored_columns`, this would result in the method returning
successfully when it should have raised, and an attribute that should
not exist written to `@attributes`.
This commit is contained in:
Sean Griffin 2018-10-30 12:52:23 -06:00
parent 9a18a10e1c
commit b63701e272
4 changed files with 16 additions and 4 deletions

View file

@ -206,6 +206,7 @@ module ActiveModel
raise ActiveModel::MissingAttributeError, "can't write unknown attribute `#{name}`"
end
alias_method :with_value_from_user, :with_value_from_database
alias_method :with_cast_value, :with_value_from_database
end
class Uninitialized < Attribute # :nodoc:

View file

@ -1,3 +1,8 @@
* `update_columns` now correctly raises `ActiveModel::MissingAttributeError`
if the attribute does not exist.
*Sean Griffin*
* Add support for hash and url configs in database hash of `ActiveRecord::Base.connected_to`.
````

View file

@ -479,15 +479,15 @@ module ActiveRecord
verify_readonly_attribute(key.to_s)
end
attributes.each do |k, v|
write_attribute_without_type_cast(k, v)
end
affected_rows = self.class._update_record(
attributes,
self.class.primary_key => id_in_database
)
attributes.each do |k, v|
write_attribute_without_type_cast(k, v)
end
affected_rows == 1
end

View file

@ -310,6 +310,12 @@ class AttributeMethodsTest < ActiveRecord::TestCase
assert_equal "New topic", topic.title
end
test "write_attribute raises ActiveModel::MissingAttributeError when the attribute does not exist" do
topic = Topic.first
assert_raises(ActiveModel::MissingAttributeError) { topic.update_columns(no_column_exists: "Hello!") }
assert_raises(ActiveModel::UnknownAttributeError) { topic.update(no_column_exists: "Hello!") }
end
test "read_attribute" do
topic = Topic.new
topic.title = "Don't change the topic"