value_to_boolean deprecated; what's a good replacement?

Chris B picture Chris B · May 31, 2013 · Viewed 10.1k times · Source

Is there a "cool-kid-approved" replacement for ActiveRecord::ConnectionAdapters::Column.value_to_boolean in rails 3.2?

Answer

John Naegle picture John Naegle · Aug 26, 2014

In Rails 4.2, this looks like a possible way to do it:

 ActiveRecord::Type::Boolean.new.type_cast_from_database(value)

Which under the covers is going to do this

if value == ''
  nil
else
  ConnectionAdapters::Column::TRUE_VALUES.include?(value)
end

Or in Rails 5:

 ActiveRecord::Type::Boolean.new.cast(value)

Which seems to end up here:

  def cast_value(value)
    if value == ''
      nil
    else
      !FALSE_VALUES.include?(value)
    end
  end