Polymorphic associations and forms

Hi,

I’ve got an issue where I’m creating a form in my view where the user
can add a Sponsorship to an Event (m2m relationship using has_many
:through). A Sponsorship belongs to an event and also belongs to a
sponsor. The sponsor is a polymorphic relationship with either a Partner
or a Company. So I have these columns set up:

Event
id
name
date

Sponsorship
event_id
sponsor_type
sponsor_id

I created a view, much like in railscasts 3-part complex forms tutorial
where I can dynamically add and remove sponsorships for the event, and
there’s a field for choosing whether the sponsorship is for a
Partner or Company and then I have 2 more fields, one with a
list of Partners and one with a list of Companies. I set up virtual
attributes in the Event model for :company_id and :partner_id and I
have logic in that model as well which wires everything up the best I
can (because of the way this is working, I couldn’t figure out how to
make everything work like magic as in the railscast, but I did get that
working for a non-polymorphic relationship elsewhere in the project).

Everything saves fine, but when I render the view, the Company and
Partner fields aren’t set to the proper values. This is because
they’re set to use :partner_id and :company_id rather than :sponsor_id.

Is there any way of doing this? anyone know where I’m going wrong?

some sample code:

the partial =>

<% fields_for 'event[sponsor_attributes][]', sponsor do |sf| -%> Sponsor <%= sf.select(:sponsor_type, @sponsor_types, { :prompt => 'Select a type...' }, :index => nil )%>
<%= label_tag 'Candidate:' %> <%= sf.select(:company_id, @companies, {:prompt => 'Choose a company...' }, :index => nil ) %>
<%= label_tag 'Partner: ' %> <%= sf.select(:partner_id, @partners, { :prompt => 'Choose a partner...' }, :index => nil ) %>
<% if sponsor.new_record? -%>
  <%= link_to_function '[-] Remove', "this.up('.sponsor').remove()"

%>
<% else -%>
<%= link_to_function ‘[-] Remove’, “mark_for_destroy(this,
‘sponsor’)” %>
<%= sf.hidden_field :id, :index => nil %>
<%= sf.hidden_field :should_destroy, :index => nil, :class =>
‘should_destroy’ %>
<% end -%>

<% end -%>

the Event model’s important stuff (yes, I know… this is a mess) =>

def sponsor_attributes=(sponsor_attributes)
sponsor_attributes.each do |attrib|
unless attrib[:sponsor_type].blank? # it’s just an empty field…
if attrib[:id].blank? # it’s a new sponsorship!
s = sponsorships.build()
else # it’s an existing sponsorship
s = sponsorships.detect { |sp| sp.id == attrib[:id].to_i }
end

    s.sponsor_type = attrib[:sponsor_type]

    # load the correct sponsor_id
    case attrib[:sponsor_type]
    when 'Company'
      s.sponsor_id = attrib[:company_id]
    when 'Partner'
      s.sponsor_id = attrib[:partner_id]
    end
  end
end

end

If I missed anything, let me know.

Thanks in advance.

…spike