views:

46

answers:

1

Hi,

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

A: 

Just figured out that rails does not supports this kind of behavior so I came up with the following workaround:

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

  def attributes=(attributes = {})
    self.client_type = attributes[:client_type]
    super
  end

  def client_attributes=(attributes)
    self.client = eval(type).find_or_initialize_by_id(attributes.delete(:client_id)) if client_type.valid?
  end
end

This gives me to set up my form like this:

<%= f.select :client_type %>
<%= f.fields_for :client do |client|%>
  <%= client.text_field :name %>
<% end %>

Not the exact solution but the idea is important.

dombesz