Merge pull request #26529 from prathamesh-sonpatki/fix-alias-attribute-issue

Check whether the current attribute being read is aliased or not before reading
This commit is contained in:
Sean Griffin 2016-12-08 13:41:36 -05:00 committed by GitHub
commit 6e948f4801
4 changed files with 43 additions and 3 deletions

@ -1,3 +1,15 @@
* Fix `write_attribute` method to check whether an attribute is aliased or not, and
use the aliased attribute name if needed.
*Prathamesh Sonpatki*
* Fix `read_attribute` method to check whether an attribute is aliased or not, and
use the aliased attribute name if needed.
Fixes #26417.
*Prathamesh Sonpatki*
* PostgreSQL & MySQL: Use big integer as primary key type for new tables
*Jon McCartie*, *Pavel Pravosud*
@ -58,7 +70,7 @@
*Jon Moss*
* Added `stat` method to `ActiveRecord::ConnectionAdapters::ConnectionPool`
* Added `stat` method to `ActiveRecord::ConnectionAdapters::ConnectionPool`.
Example:

@ -48,7 +48,12 @@ def #{temp_method}
# it has been typecast (for example, "2004-12-12" in a date column is cast
# to a date object, like Date.new(2004, 12, 12)).
def read_attribute(attr_name, &block)
name = attr_name.to_s
name = if self.class.attribute_alias?(attr_name)
self.class.attribute_alias(attr_name).to_s
else
attr_name.to_s
end
name = self.class.primary_key if name == "id".freeze
_read_attribute(name, &block)
end

@ -29,7 +29,13 @@ def __temp__#{safe_name}=(value)
# specified +value+. Empty strings for Integer and Float columns are
# turned into +nil+.
def write_attribute(attr_name, value)
write_attribute_with_type_cast(attr_name, value, true)
name = if self.class.attribute_alias?(attr_name)
self.class.attribute_alias(attr_name).to_s
else
attr_name.to_s
end
write_attribute_with_type_cast(name, value, true)
end
def raw_write_attribute(attr_name, value) # :nodoc:

@ -319,6 +319,13 @@ def setup
assert_equal "Still another topic: part 4", topic.title
end
test "write_attribute can write aliased attributes as well" do
topic = Topic.new(title: "Don't change the topic")
topic.write_attribute :heading, "New topic"
assert_equal "New topic", topic.title
end
test "read_attribute" do
topic = Topic.new
topic.title = "Don't change the topic"
@ -329,6 +336,16 @@ def setup
assert_equal "Don't change the topic", topic[:title]
end
test "read_attribute can read aliased attributes as well" do
topic = Topic.new(title: "Don't change the topic")
assert_equal "Don't change the topic", topic.read_attribute("heading")
assert_equal "Don't change the topic", topic["heading"]
assert_equal "Don't change the topic", topic.read_attribute(:heading)
assert_equal "Don't change the topic", topic[:heading]
end
test "read_attribute raises ActiveModel::MissingAttributeError when the attribute does not exist" do
computer = Computer.select("id").first
assert_raises(ActiveModel::MissingAttributeError) { computer[:developer] }