Skip to content

Instantly share code, notes, and snippets.

@rmw
Created September 29, 2011 20:37
Show Gist options
  • Save rmw/1251863 to your computer and use it in GitHub Desktop.
Save rmw/1251863 to your computer and use it in GitHub Desktop.
Validate a polymorphic association for a new record
class Address < ActiveRecord::Base
belongs_to :addressable, :polymorphic => true
#use these instead of validates_presence_of :addressable
validates_presence_of :addressable_type
validates_presence_of :addressable_id, :unless => Proc.new { |a|
#if it's a new record and addressable is nil and addressable_type is set
# then try to find the addressable object in the ObjectSpace
# if the addressable object exists, then we're valid;
# if not, let validates_presence_of do it's thing
if (new_record? && !addressable && addressable_type)
addressable = nil
ObjectSpace.each_object(addressable_type.constantize) do |o|
addressable = o if o.addresses.include?(a) unless addressable
end
end
addressable
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment