Validate presence of polymorphic parent

后端 未结 5 912
耶瑟儿~
耶瑟儿~ 2021-02-19 09:49

I am developing a Rails 3.2 application with the following models:

class User < ActiveRecord::Base
  # Associations
  belongs_to :authenticatable, polymorphic         


        
5条回答
  •  我在风中等你
    2021-02-19 10:12

    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
        }
    

提交回复
热议问题