accepts_nested_attributes_for with belongs_to polymorphic

后端 未结 4 680
渐次进展
渐次进展 2020-11-27 10:37

I would like set up a polymorphic relation with accepts_nested_attributes_for. Here is the code:

class Contact 

        
4条回答
  •  鱼传尺愫
    2020-11-27 11:09

    I've also had a problem with the "ArgumentError: Cannot build association model_name. Are you trying to build a polymorphic one-to-one association?"

    And I found a better solution for this kind of problem. You can use native method. Lets look to the nested_attributes implementation, inside Rails3:

    elsif !reject_new_record?(association_name, attributes)
      method = "build_#{association_name}"
      if respond_to?(method)
        send(method, attributes.except(*UNASSIGNABLE_KEYS))
      else
        raise ArgumentError, "Cannot build association #{association_name}. Are you trying to build a polymorphic one-to-one association?"
      end
    end
    

    So actually what do we need to do here? Is just to create build_#{association_name} inside our model. I've did totally working example at the bottom:

    class Job  :true
    
      accepts_nested_attributes_for :client
    
      protected
    
      def build_client(params, assignment_options)
        raise "Unknown client_type: #{client_type}" unless CLIENT_TYPES.include?(client_type)
        self.client = client_type.constantize.new(params)
      end
    end
    

提交回复
热议问题