Validate presence of polymorphic parent

后端 未结 5 946
耶瑟儿~
耶瑟儿~ 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:17

    I was able to get this to work by overriding the nested attribute setter.

    class Physician
      has_one :user, as: :authenticatable
      accepts_nested_attributes_for :user
    
      def user_attributes=(attribute_set)
        super(attribute_set.merge(authenticatable: self))
      end
    end
    

    To DRY it up, I moved the polymorphic code to a concern:

    module Authenticatable
      extend ActiveSupport::Concern
    
      included do
        has_one :user, as: :authenticatable
        accepts_nested_attributes_for :user
    
        def user_attributes=(attribute_set)
          super(attribute_set.merge(authenticatable: self))
        end
      end
    end
    
    class Physician
      include Authenticatable
      ...
    end
    

    For has_many associations, the same can be accomplished with a map:

    class Physician
      has_many :users, as: :authenticatable
      accepts_nested_attributes_for :users
    
      def users_attributes=(attribute_sets)
        super(
          attribute_sets.map do |attribute_set|
            attribute_set.merge(authenticatable: self)
          end
        )
      end
    end
    
    class User
      belongs_to :authenticatable, polymorphic: true
      validates :authenticatable, presence: true
    end
    

    All that said, I think konung's last comment is correct - your example does not look like a good candidate for polymorphism.

提交回复
热议问题