例如,假设我有一个带有整数列'pet_id'的用户模型。
如果我跑
user = User.new
user.update_attribute(:pet_id, '1')
它会自动将字符串'1'转换为整数1.这种转换在哪里发生?
答案 0 :(得分:3)
这是负责活动记录中type_cast
的方法
def type_cast(value)
return nil if value.nil?
return coder.load(value) if encoded?
klass = self.class
case type
when :string, :text then value
when :integer then klass.value_to_integer(value)
when :float then value.to_f
when :decimal then klass.value_to_decimal(value)
when :datetime, :timestamp then klass.string_to_time(value)
when :time then klass.string_to_dummy_time(value)
when :date then klass.value_to_date(value)
when :binary then klass.binary_to_string(value)
when :boolean then klass.value_to_boolean(value)
else value
end
end
要详细了解rails
activerecord
type_cast
,请访问这三个网站
1)Thoughtbot博客How Rails' Type Casting Works
2)Ken Collins ActiveRecord 4.2's Type Casting
3)github
中的Railsactiverecord
类型转换方法