views:

28

answers:

2

This is probably a simple question, but I noticed a few errors deriving from having empty values instead of nils...

If a user leaves a field blank in a standard rails app is there a way to leave the field in the database set to NULL instead of entering an empty value?

Basically so a check like @model.info.nil? return true instead of having to check if it is both nil and empty?

+1  A: 

edit As brokenbeatnik noted, I confused blank? with empty?, my bad.

You don't have to check both nil and empty values. var.empty? will return true even for nil (see API docs). So, I usually find it more convenient to use empty check only.

But if you don't want that, you can convert empty values to nils with active record callbacks. Something like attribute = nil if attribute.empty? each time before object is saved.

edit guides.rubyonrails.org has some problems, but you can use google cache: http://webcache.googleusercontent.com/search?sourceid=chrome&ie=UTF-8&q=cache:http://guides.rubyonrails.org/activerecord_validations_callbacks.html%23available-callbacks

Nikita Rybak
+2  A: 

I use var.blank?, because I get these results in a Rails 3 console running against Ruby 1.8:

>> nil.blank?
=> true
>> [].blank?
=> true
>> nil.empty?
NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.empty?
        from (irb):4

Historically, I haven't seen .empty? work for nil objects.

brokenbeatnik
Thanks for pointing that out, it should be blank? indeed.
Nikita Rybak