accepts_nested_attributes_for with belongs_to polymorphic

dombesz picture dombesz · Oct 19, 2010 · Viewed 23.4k times · Source

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

class Contact <ActiveRecord::Base
  has_many :jobs, :as=>:client
end

class Job <ActiveRecord::Base
  belongs_to :client, :polymorphic=>:true
  accepts_nested_attributes_for :client
end

When I try to access Job.create(..., :client_attributes=>{...} gives me NameError: uninitialized constant Job::Client

Answer

Dmitry Polushkin picture Dmitry Polushkin · Aug 9, 2011

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