Skip to content

Commit

Permalink
Fix bug when Column is trying to type cast boolean values to integer.
Browse files Browse the repository at this point in the history
This can occur if the user is using :integer columns to store boolean
values. Now we are handling the boolean values but it still raises if
the value can't type cast to integer and is not a boolean. See #7509.

Fixes #8067.

Conflicts:
	activerecord/CHANGELOG.md
  • Loading branch information
rafaelfranca committed Oct 30, 2012
1 parent a4ac2b4 commit 3525a9b
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
15 changes: 13 additions & 2 deletions activerecord/lib/active_record/connection_adapters/column.rb
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def type_cast(value)

case type
when :string, :text then value
when :integer then value.to_i
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)
Expand All @@ -115,7 +115,7 @@ def type_cast_code(var_name)

case type
when :string, :text then var_name
when :integer then "(#{var_name}.to_i)"
when :integer then "#{klass}.value_to_integer(#{var_name})"
when :float then "#{var_name}.to_f"
when :decimal then "#{klass}.value_to_decimal(#{var_name})"
when :datetime, :timestamp then "#{klass}.string_to_time(#{var_name})"
Expand Down Expand Up @@ -198,6 +198,17 @@ def value_to_boolean(value)
end
end

# Used to convert values to integer.
# handle the case when an integer column is used to store boolean values
def value_to_integer(value)
case value
when TrueClass, FalseClass
value ? 1 : 0
else
value.to_i
end
end

# convert something to a BigDecimal
def value_to_decimal(value)
# Using .class is faster than .is_a? and
Expand Down
8 changes: 4 additions & 4 deletions activerecord/test/cases/column_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ def test_type_cast_integer
assert_equal 0, column.type_cast('bad1')
assert_equal 0, column.type_cast('bad')
assert_equal 1, column.type_cast(1.7)
assert_equal 0, column.type_cast(false)
assert_equal 1, column.type_cast(true)
assert_nil column.type_cast(nil)
end

Expand All @@ -41,11 +43,9 @@ def test_type_cast_non_integer_to_integer
assert_raises(NoMethodError) do
column.type_cast([])
end

assert_raises(NoMethodError) do
column.type_cast(true)
end
assert_raises(NoMethodError) do
column.type_cast(false)
column.type_cast(Object.new)
end
end

Expand Down

0 comments on commit 3525a9b

Please sign in to comment.