I tried to use Ruby on Rails with Microsoft SQLServer recently, and I kept having problems with my "bit" fields. Looking on the web, the Rails repository claims to have fixed this, so I downloaded the new adapter from svn. It didn't work for me, so I started hacking. I really need to send this as a diff to the ActiveRecord maintainers, with test code to prove that it works. By the way, I am using ADO mode ... maybe their original code works for ODBC mode. I suspect that tests should be run for both modes. Anyway, enough chatter, here is the fix!
In file sqlserver_adapter.rb, add the #cast_to_bit and modify #quote as following:
Update: Check my new blog entry for more on booleans. How does Rails scaffolding select HTML input tags?
Update2: As of Dec 8, 2005, the Rails 0.14.3 has changed the SqlServer adapter. My boolean fix may not be required (I haven't tested it yet).
In file sqlserver_adapter.rb, add the #cast_to_bit and modify #quote as following:
def cast_to_bit(value)
case value
when nil then nil
when '1' then 1
when '0' then 0
when 1 then 1
when 0 then 0
when 'true' then 1
when 'false' then 0
else
# puts "Invalid Boolean #{value}"
0
end
end
def quote(value, column = nil)
case value
when String
if column && column.type == :binary
"'#{quote_string(column.string_to_binary(value))}'"
elsif column && column.type == :boolean
"#{column.cast_to_bit(value)}"
else
"'#{quote_string(value)}'"
end
when NilClass then "NULL"
when TrueClass then '1'
when FalseClass then '0'
when Float, Fixnum, Bignum then value.to_s
when Date then "'#{value.to_s}'"
when Time, DateTime then "'#{value.strftime("%Y-%m-%d %H:%M:%S")}'"
else "'#{quote_string(value.to_yaml)}'"
end
end
Update: Check my new blog entry for more on booleans. How does Rails scaffolding select HTML input tags?
Update2: As of Dec 8, 2005, the Rails 0.14.3 has changed the SqlServer adapter. My boolean fix may not be required (I haven't tested it yet).
Comments
Why doesn't rails display a checkbox for booleans/bit fields?
Thanks again.