jeroenh-2c0CEBhyA8t7k3Vc6bgG2UEOCMrvLtNR@public.gmane.org
2005-Oct-22 11:54 UTC
Storing empty input fields with NULL?
What would be the easiest way to store empty input fields from a form into the database as "NULL" values? By default, Rails uses the empty strings for such fields when using update_attributes. I''ve solved the problem already, using a before_update on the model that sets fields containing an empty string to nil, but maybe there''s an easier way to do this? thanks, Jeroen Heijmans
Julian ''Julik'' Tarkhanov
2005-Oct-22 17:35 UTC
Re: Storing empty input fields with NULL?
On 22-okt-2005, at 13:54, jeroenh-2c0CEBhyA8t7k3Vc6bgG2UEOCMrvLtNR@public.gmane.org wrote:> What would be the easiest way to store empty input fields from a > form into > the database as "NULL" values? By default, Rails uses the empty > strings > for such fields when using update_attributes. > > I''ve solved the problem already, using a before_update on the model > that > sets fields containing an empty string to nil, but maybe there''s an > easier > way to do this?Long ago this also hindered validations, since then I always use this dropin code in every Rails app I deploy class ActiveRecord::Base before_validation :strip_whitespace_from_attributes # Will strip trailing and leading whitespace from all attributes and convert # empty strings to nil and symbols to strings def strip_whitespace_from_attributes for col in self.class.content_columns.collect{|c| c.name.to_sym} if !self[col].nil? && self[col].respond_to?(:strip) s = self.send(col).strip.gsub("\r\n", "\n").gsub("\r", "\n").gsub("\r", "\n") s.size == 0 ? self[col] = nil : self[col] = s end for col in self.class.content_columns.collect{|c| c.name.to_sym} self[col] = self[col].to_s if self[col].is_a?(Symbol) end end end end -- Julian "Julik" Tarkhanov