Ruby on rails 属性查询方法是如何工作的?
即是Ruby on rails 属性查询方法是如何工作的?,ruby-on-rails,Ruby On Rails,即是 Post.title? 相当于 Post.title.present? 没有 Object#present?与调用是一样的!对象为空? “attribute?”方法可能会调用相同的代码,但可能不会,这取决于所处理的列类型 要查看这些字段是否返回相同的值,最简单的方法是访问数字列。假设您的数据库中有foo.score作为十进制列,并将其设置为零。您将看到以下行为 foo.score = 0 foo.score? # false foo.score.present? # true “?
Post.title?
相当于
Post.title.present?
没有
Object#present?
与调用是一样的!对象为空?
“attribute?”方法可能会调用相同的代码,但可能不会,这取决于所处理的列类型
要查看这些字段是否返回相同的值,最简单的方法是访问数字列。假设您的数据库中有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
至少在3.2中,“?”的代码现在存储在ActiveRecord::AttributeMethods::Query中