Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails nils in a form

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?

like image 446
holden Avatar asked Sep 03 '10 19:09

holden


2 Answers

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.

like image 119
brokenbeatnik Avatar answered Nov 08 '22 12:11

brokenbeatnik


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.

like image 1
Nikita Rybak Avatar answered Nov 08 '22 13:11

Nikita Rybak