Save blank value as nil in database
I have a web开发者_Python百科 page where some information are asked. But some value can be blank. But if I save more than once my formulary with some blank value if says that Value has been already taken. This is normal since I used: validates_uniqueness_of
My question is: if I save value as nil, does this problem will be solved ?? If yes how save value as nil. Or what are others solutions please ??
Thanks in advance.
I'd personally not use the validation with :allow_blank
as vise did and have a before_validation callback which set the value to nil if value.blank?
Something like:
private
def strip_spaces
attrib = nil if attrib.blank?
end
The reasoning for this is that queries to find those where the value is not set would be of the kind where attrib is null
instead of where trim(attrib) = '' or attrib is null
It's in the docs.
validates_uniqueness_of :my_value, :allow_blank => true
精彩评论