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

Raise MissingAttributeError on query methods

When calling a query method on an attribute that was not selected by
an ActiveRecord query, an ActiveModel::MissingAttributeError is not
raised. Instead, a nil value is returned, which will return false once
cast to boolean.

This is undesirable, as we should not give the impression that we know
the attribute's boolean value when we haven't loaded the attribute's
(possibly) non-boolean value from the database.

This issue is present on versions going back as far as 2.3, at least.
This commit is contained in:
Ernie Miller 2012-09-06 15:39:42 -04:00
parent f6296601a2
commit 4f107da4ff
3 changed files with 8 additions and 1 deletions

View file

@ -1,5 +1,11 @@
## Rails 4.0.0 (unreleased) ##
* Attribute predicate methods, such as `article.title?`, will now raise
`ActiveModel::MissingAttributeError` if the attribute being queried for
truthiness was not read from the database, instead of just returning false.
*Ernie Miller*
* `ActiveRecord::SchemaDumper` uses Ruby 1.9 style hash, which means that the
schema.rb file will be generated using this new syntax from now on.

View file

@ -8,7 +8,7 @@ module ActiveRecord
end
def query_attribute(attr_name)
value = read_attribute(attr_name)
value = read_attribute(attr_name) { |n| missing_attribute(n, caller) }
case value
when true then true

View file

@ -276,6 +276,7 @@ class FinderTest < ActiveRecord::TestCase
def test_find_only_some_columns
topic = Topic.all.merge!(:select => "author_name").find(1)
assert_raise(ActiveModel::MissingAttributeError) {topic.title}
assert_raise(ActiveModel::MissingAttributeError) {topic.title?}
assert_nil topic.read_attribute("title")
assert_equal "David", topic.author_name
assert !topic.attribute_present?("title")