rails nils in a form
This is probably a simple question, but I noticed a few errors deriving from having empty values instead of n开发者_Go百科ils...
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?
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.
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.
精彩评论