Skip to content

Commit

Permalink
Make ActiveRecord::AttributeMethods::Query respect getter overwrites …
Browse files Browse the repository at this point in the history
…in the model
  • Loading branch information
Felipe committed Dec 28, 2020
1 parent 96446a9 commit e3fc1e6
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 1 deletion.
25 changes: 25 additions & 0 deletions activerecord/CHANGELOG.md
@@ -1,3 +1,28 @@
* Makes `ActiveRecord::AttributeMethods::Query` respect the getter overrides defined in the model.

Fixes #40771.

Before:

```ruby
class User

def admin
false # Overriding the getter to always return false
end

end

user = User.first
user.update(admin: true)

user.admin # false (as expected, due to the getter overwrite)
user.admin? # true (not expected, returned the DB column value)

```

After this commit, `user.admin?` above returns false, as expected.

* Allow delegated_type to be specified primary_key and foreign_key.

Since delegated_type assumes that the foreign_key ends with `_id`,
Expand Down
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/attribute_methods/query.rb
Expand Up @@ -10,7 +10,7 @@ module Query
end

def query_attribute(attr_name)
value = self[attr_name]
value = self.public_send(attr_name)

case value
when true then true
Expand Down
17 changes: 17 additions & 0 deletions activerecord/lib/active_record/base.rb
Expand Up @@ -137,6 +137,23 @@ module ActiveRecord #:nodoc:
# anonymous = User.new(name: "")
# anonymous.name? # => false
#
# Query methods will also respect any overwrites of default accessors:
#
# class User
# # Has admin boolean column
# def admin
# false
# end
# end
#
# user.update(admin: true)
#
# user.read_attribute(:admin) # => true, gets the column value
# user[:admin] # => true, also gets the column value
#
# user.admin # => false, due to the getter overwrite
# user.admin? # => false, due to the getter overwrite
#
# == Accessing attributes before they have been typecasted
#
# Sometimes you want to be able to read the raw attribute data without having the column-determined
Expand Down
10 changes: 10 additions & 0 deletions activerecord/test/cases/attribute_methods_test.rb
Expand Up @@ -429,6 +429,16 @@ def topic.title() "b" end
assert_equal "a", topic[:title]
end

test "read overriden attribute with predicate respects override" do
topic = Topic.new

topic.approved = true

def topic.approved; false; end

assert_not topic.approved?, "overriden approved should be false"
end

test "string attribute predicate" do
[nil, "", " "].each do |value|
assert_equal false, Topic.new(author_name: value).author_name?
Expand Down

0 comments on commit e3fc1e6

Please sign in to comment.