I have a AR model with several string (VARCHAR(255)) fields which are
NULLable.
When I create a new model using Blah.new, some of my attributes are set
to empty string ("") instead of nil. I can’t figure out why.
The attributes that get set to empty string are “address1”, “city”,
“state” and “zip_code”. But none of the other attributes, which are
also VARCHAR(255) and allowed to be NULL, get set to an empty string.
Model is below.
Any ideas?
===============================================================================
== Schema Information
Schema version: 31
Table name: insureds
id :integer(11) not null, primary key
name :string(255) default(), not null
dba_name :string(255)
address1 :string(255)
address2 :string(255)
city :string(255)
state :string(255)
zip_code :string(255)
quote_input_id :integer(11) default(0), not null
created_at :datetime
updated_at :datetime
phone :string(255)
business_type :string(255)
mailing_address1 :string(255)
mailing_address2 :string(255)
mailing_city :string(255)
mailing_state :string(255)
mailing_zip_code :string(255)
class Insured < ActiveRecord::Base
belongs_to :quote_input
validates_presence_of :name
validates_format_of :mailing_zip_code,
:message => ‘is invalid’,
:with => /^\d{5}$|^\d{5}-?\d{4}$|^$/
validates_format_of :zip_code,
:message => ‘is invalid’,
:with => /^\d{5}$|^\d{5}-?\d{4}$|^$/
BUSINESS_TYPES = [[‘Corporation’, ‘Corporation’],
[‘Partnership’, ‘Partnership’],
[‘Joint Venture’, ‘Joint Venture’],
[‘Individual’, ‘Individual’],
[‘Other organization’, ‘Other organization’]]
def display_city
read_attribute(:city) && read_attribute(:city) != ‘’ && self.valid?
? city : ’ (Enter ZIP code)’
end
def display_city=(new_city)
write_attribute(:city, new_city) unless new_city =~ /(Enter ZIP
code)/
end
def mailing_display_city
read_attribute(:mailing_city) && read_attribute(:mailing_city) != ‘’
&& self.valid? ? mailing_city : ’ (Enter ZIP code)’
end
def mailing_display_city=(new_city)
write_attribute(:mailing_city, new_city) unless new_city =~ /(Enter
ZIP code)/
end
def zip_code=(new_zip_code)
if new_zip_code =~ /^\d{9}$/
new_zip_code = “#{new_zip_code[0,5]}-#{new_zip_code[5,4]}”
end
write_attribute(:zip_code, new_zip_code)
end
def mailing_zip_code=(new_zip_code)
if new_zip_code =~ /^\d{9}$/
new_zip_code = “#{new_zip_code[0,5]}-#{new_zip_code[5,4]}”
end
write_attribute(:mailing_zip_code, new_zip_code)
end
end