#<ActiveRecord::ConnectionAdapters::Column> 的未定义方法“type_cast”(NoMethodError)

undefined method `type_cast' for #<ActiveRecord::ConnectionAdapters::Column> (NoMethodError)

ActiveRecord::ConnectionAdapters::Column 曾经有一个名为 type_cast 的方法,它接受一个字符串并将其转换为 "to an appropriate instance"。这似乎在某个时候被删除了,我不知道我应该做什么来替换它。

这是使用它的代码:

  # Create a column that will be responsible for typecasting
  @column = ActiveRecord::ConnectionAdapters::Column.new(attribute.to_s, options[:default], @type == 'any' ? nil : @type)

  # Typecasts the value based on the type of preference that was defined
  def type_cast(value)
    if @type == 'any'
      value
    else
      @column.type_cast(value)
    end
  end

我正在使用 Rails/ActiveRecord 4.2.10.

这里有一个列表:typecast alternatives,但据我所知,它不是特别有用。

预计到达时间:目前,我已经复制了原始 type_cast 中的代码并对其进行了修改以在本地使用。但如果有真正的解决方案,我更愿意。

ActiveRecord::ConnectionAdapters::Column#type_cast 已删除/移动到 API 的其他部分,包括 type_cast_for_databasetype_cast_for_schema.

等内容

您可以在连接上使用 type_cast,如下所示:

@column = ActiveRecord::ConnectionAdapters::Column.new(attribute.to_s, options[:default], @type == 'any' ? nil : @type)

# Typecasts the value based on the type of preference that was defined
def type_cast(value)
  if @type == 'any'
    value
  else
    ActiveRecord::Base.connection.type_cast(value, @column) # <---- HERE
  end
end

如果您有兴趣,可以在 _type_cast and type_cast 深入了解内部结构。