How do attribute query methods work?

Ie, is

Post.title?

      

equivalent to

Post.title.present?

      

+2


source to share


1 answer


Not.

Object#present?

is the same as a challenge !obj.blank?

.

"Attribute?" the method may end up calling the same code, but it may or may not, and it depends on the type of column you are dealing with.

The easiest way to see that they don't return the same value is by accessing a numeric column. Let's say you have foo.score

as a decimal column in your db and you set it to zero. You will see the following behavior.



foo.score = 0
foo.score? # false
foo.score.present?  # true

      

Code for "?" the method is in ActiveRecord :: AttributeMethods.

def query_attribute(attr_name)
  unless value = read_attribute(attr_name)
    false
  else
    column = self.class.columns_hash[attr_name]
    if column.nil?
      if Numeric === value || value !~ /[^0-9]/
        !value.to_i.zero?
      else
        return false if ActiveRecord::ConnectionAdapters::Column::FALSE_VALUES.include?(value)
        !value.blank?
      end 
    elsif column.number?
      !value.zero?
    else
      !value.blank?
    end 
  end 
end 

      

+4


source







All Articles