I am developing a Rails 3.2 application with the following models:
class User < ActiveRecord::Base
# Associations
belongs_to :authenticatable, polymorphic
I'm not sure if this solves your problem, but I use something like this when validating that a polymorphic parent exists.
Here is some code that I used in a video
model with the parent
as the polymorphic association. This went in video.rb
.
validates_presence_of :parent_id, :unless => Proc.new { |p|
# if it's a new record and parent is nil and addressable_type is set
# then try to find the parent object in the ObjectSpace
# if the parent object exists, then we're valid;
# if not, let validates_presence_of do it's thing
# Based on http://www.rebeccamiller-webster.com/2011/09/validate-polymorphic/
if (new_record? && !parent && parent_type)
parent = nil
ObjectSpace.each_object(parent_type.constantize) do |o|
parent = o if o.videos.include?(p) unless parent
end
end
parent
}