2009-09-24 63 views

回答

4

Object#present?是一回事調用!obj.blank?

「屬性?」方法最終可能會調用相同的代碼,但它可能不會,並且取決於您正在處理的列類型。

查看這些不返回相同值的最簡單方法是訪問數字列。假設你的數據庫中有foo.score作爲十進制列,並將其設置爲零。你會看到以下行爲。

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

代碼「?」方法在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 
+1

至少3.2,代碼「?」現在存儲在ActiveRecord :: AttributeMethods :: Query中 – toxaq 2013-01-29 03:46:12