Monday, March 16, 2009

Handel database NULL values in rails

I was in the impression that rails takes care of

1) nil to NULL when inserting, and

2) NULL to nil while fetching records through Active record

But this proved wrong when my application running in SQL server 2005 fails to detect database NULL fetched from DB.

The fetched value was not even caught by blank? method.

Found this article while googling on this issue, this more or less matched the problem I was facing.

I tried it and was successful.

I am providing a snapshot of the article
ActiveRecord::Base.class_eval do
def attributes_from_column_definition_with_null_fix
returning attributes = attributes_from_column_definition_without_null_fix do
attributes.each_value { |value| value.replace('') if value == 'NULL' }

alias_method_chain :attributes_from_column_definition, :null_fix

This helped me in dealing with DB NULL values. Certainly without this article it would have been a tough going to find a way around for this issue ;).

Have also made a thread for this in WorkingWithRails, just to make sure the fix is valid and to get expert comments on the fix.

No comments: