Skip to content

Loading…

Update ActiveRecord#attribute_present? to work as documented #3535

Merged
merged 1 commit into from

2 participants

@jmazzi

RIght now attribute_present? returns false for "false" values. Since "false" is a value you can set in the db it should return true when it's set.

"Returns true if the specified attribute has been set by the user or by
a database load and is neither nil nor empty?"

Fixes #1613

@jmazzi jmazzi Update ActiveRecord#attribute_present? to work as documented
"Returns true if the specified attribute has been set by the user or by
a database load and is neither nil nor empty?"

Fixes #1613
c7d2078
@jonleighton jonleighton merged commit 62512b9 into rails:master
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Nov 6, 2011
  1. @jmazzi

    Update ActiveRecord#attribute_present? to work as documented

    jmazzi committed
    "Returns true if the specified attribute has been set by the user or by
    a database load and is neither nil nor empty?"
    
    Fixes #1613
Showing with 20 additions and 1 deletion.
  1. +2 −1 activerecord/lib/active_record/base.rb
  2. +18 −0 activerecord/test/cases/attribute_methods_test.rb
View
3 activerecord/lib/active_record/base.rb
@@ -1771,7 +1771,8 @@ def attribute_for_inspect(attr_name)
# Returns true if the specified +attribute+ has been set by the user or by a database load and is neither
# nil nor empty? (the latter only applies to objects that respond to empty?, most notably Strings).
def attribute_present?(attribute)
- !_read_attribute(attribute).blank?
+ value = _read_attribute(attribute)
+ !value.nil? || (value.respond_to?(:empty?) && !value.empty?)
end
# Returns the column object for the named attribute.
View
18 activerecord/test/cases/attribute_methods_test.rb
@@ -35,6 +35,24 @@ def test_attribute_present
assert !t.attribute_present?("content")
end
+ def test_attribute_present_with_booleans
+ b1 = Boolean.new
+ b1.value = false
+ assert b1.attribute_present?(:value)
+
+ b2 = Boolean.new
+ b2.value = true
+ assert b2.attribute_present?(:value)
+
+ b3 = Boolean.new
+ assert !b3.attribute_present?(:value)
+
+ b4 = Boolean.new
+ b4.value = false
+ b4.save!
+ assert Boolean.find(b4.id).attribute_present?(:value)
+ end
+
def test_attribute_keys_on_new_instance
t = Topic.new
assert_equal nil, t.title, "The topics table has a title column, so it should be nil"
Something went wrong with that request. Please try again.