Friday, October 14, 2005

Rails connection_adapter SqlServer fix for boolean fields

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:

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
# puts "Invalid Boolean #{value}"

def quote(value, column = nil)
case value
when String
if column && column.type == :binary
elsif column && column.type == :boolean
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)}'"

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).


Blogger matt said...

This works great. Thanks for the fix.

Why doesn't rails display a checkbox for booleans/bit fields?

Thanks again.

October 24, 2005 1:26 PM  
Blogger Roy Tate said...

You're welcome, matt. I hope my Nov 15th blog entry helps some.

November 15, 2005 4:42 PM  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home