class Address < ActiveRecord::Base has_one :company, :dependent => :destroy has_many :people validates_presence_of :street_1, :message => "Please enter an initial line for the address" POSTCODE_REGEX = /^[A-Z][A-Z]?[0-9][A-Z0-9]? ?[0-9][ABDEFGHJLNPQRSTUWXYZ]{2}$/i validates_format_of :post_code, :with => POSTCODE_REGEX, :message => "Please enter a valid post code" def validate_on_create if Address.find_by_street_1_and_post_code(street_1, post_code) errors.add_to_base('Street address and post code already exist in the database') end end # Look up or initialize an address from params if street_1 or post_code supplied; # otherwise return nil; NB does not save the address def self.from_street_1_and_post_code(params) params ||= {} street_1 = params[:street_1] post_code = params[:post_code] if street_1.blank? and post_code.blank? address = nil else address = find_or_initialize_by_street_1_and_post_code(street_1, post_code) address.attributes = params end address end end