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

折月煮酒 提交于 2019-12-13 01:43:53

问题


ActiveRecord::ConnectionAdapters::Column used to have a method called type_cast which took a string and cast it "to an appropriate instance". This appears to have been removed at some point, and I can't figure out what I should do to replace it.

Here is the code that uses it:

  # 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

I'm using Rails/ActiveRecord 4.2.10.

There's a list here: typecast alternatives, but it's not particularly useful, so far as I can tell.

ETA: For now, I've copied the code from the original type_cast and modified it to use it locally. But if there's a real solution, I'd prefer that.


回答1:


ActiveRecord::ConnectionAdapters::Column#type_cast was removed / moved to other parts of the API, including things like type_cast_for_database or type_cast_for_schema.

You can use the type_cast on the connection though, like this:

@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

You can dig in the internals at _type_cast and type_cast if you are curious.



来源:https://stackoverflow.com/questions/51884908/undefined-method-type-cast-for-activerecordconnectionadapterscolumn-no

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!