Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 492
user19230 Avatar asked Sep 12 '25 00:09

user19230


1 Answers

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.

like image 159
dgilperez Avatar answered Sep 14 '25 21:09

dgilperez