accepts_nested_attributes_for with belongs_to polymorphic

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 <ActiveRecord::Base
  CLIENT_TYPES = %w(Contact)

  attr_accessible :client_type, :client_attributes

  belongs_to :client, :polymorphic => :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

Leave a Comment