views:

155

answers:

2

I'm running into to a issue with a nested form which I'm sure should be easily solved, yet I can't find a way around it

Basically I have the following relationship

event has_many :contacts => through :event_contacts

the nested form works perfectly as long as I'm creating new contacts each time.

If I include a drop down to allow selection of an existing contact within the nested form, an event is created, however the contact_id is nil in the event_contacts table.

No contact is created, since I post an 'id' field for the nested contact.. (ie .new_record? returns false.)

So how do I update the event_contacts table to ensure that the 'selected' contacts is properly associated?

See snipbits below...

Models

class Event < ActiveRecord::Base
  belongs_to  :user

  has_many    :event_contacts
  accepts_nested_attributes_for :event_contacts 

  has_many    :contacts, :through => :event_contacts
  accepts_nested_attributes_for :contacts


class EventContact < ActiveRecord::Base
  belongs_to :event
  belongs_to :contact

  accepts_nested_attributes_for :contact


class Contact < ActiveRecord::Base
  belongs_to  :user

  has_many    :event _contacts
  has_many    :events, :through => :event_contacts

View

- fields_for(@event) do |f|
  - f.fields_for :event_contacts do |rc|
    - rc.fields_for :contact do |c|
      = c.collection_select :id, Contact.all, :id, :name, { :selected => @contact.id || 0 }

      = c.hidden_field :user_id, :value => @current_user.id 
      = c.text_field :first_name
          = c.text_field :email
A: 

did you include the accepts_nested_attributes in you model?

Lichtamberg
yes, have include this in the parent model (event) and the join model also (event_contact)
Dom
Why do you use a seperate model? You could use a hbtm relation and remove this one model (evencontact)
Lichtamberg
want to store more information in the join model which doesn't fit into either the event or contact model
Dom
A: 

Not quite the answer I was looking for .. but have hacked my way aroung this using a post save method in the parent controller (event) and checking through the child objects to inspect if the contact was new or existing..

I then update the intemediary table event_contacts manually...

Not the most elegant solution but it works and allows me to move on...

Still would appreciate any guidance as to how to do this the rails way..

Dom