Skip to content

Instantly share code, notes, and snippets.

@jimmybaker
Forked from rubysolo/gist:129810
Created June 14, 2009 21:56
Show Gist options
  • Save jimmybaker/129834 to your computer and use it in GitHub Desktop.
Save jimmybaker/129834 to your computer and use it in GitHub Desktop.
class Address < ActiveRecord::Base
belongs_to :addressable, :polymorphic => true
named_scope :default, :conditions => { :default => true }
named_scope :without, lambda{|address| { :conditions => ["id <> ?", address.to_param] }}
before_save :set_default
private
def set_default
return true unless addressable.kind_of? User
if default?
addressable.addresses.default.without(self).each{|a| a.update_attribute(:default, false) }
else
default = true if new_record? && addressable.addresses.default.empty?
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment