Created
September 29, 2011 20:37
-
-
Save rmw/1251863 to your computer and use it in GitHub Desktop.
Validate a polymorphic association for a new record
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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