2016-01-23 56 views

回答

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 

要了解railsactiverecordtype_cast的详情,请访问这三个地点

1)Thoughtbot博客How Rails' Type Casting Works

2)肯柯林斯ActiveRecord 4.2's Type Casting

3)导轨activerecord类型转换方法github