How can I add two models in one form, where one model is a has_many :through?
- by Angela
How do I model having multiple Addresses for a Company and assign a single Address to a Contact?
Contacts belong_to a Company.
A Company has_many Contacts.
A Company also has_many Addresses.
And each Contact has_one Address.
I want to be able, whenever I create a New Contact, to access all the addresses in all Contacts that belong to the Company.
Here is are my Models:
class Company < ActiveRecord::Base
attr_accessible :name, :phone, :addresses
has_many :contacts
has_many :addresses, :through => :contacts
end
class Contact < ActiveRecord::Base
attr_accessible :first_name, :last_name, :title, :phone, :fax, :email, :company,
:date_entered, :campaign_id, :company_name, :address
belongs_to :company
has_one :address
accepts_nested_attributes_for :address
end
class Address < ActiveRecord::Base
attr_accessible :street1
has_many :contacts
end
How do I create the View in the _form for Contacts so that I can 1) Add an Address when creating a Contact; 2) Display the options of the Address.
Here is how I am doing step 1, which is just to add a new address for a new contact:
<% f.fields_for :addresses do |builder| %>
<p>
<%= builder.label :street1, "Street 1" %> </br>
<%= builder.text_field :street1 %>
<p>
Right now, what I have doesn't work. The console says I cannot mass-assign addresses when I hit "submit" on this New contact form.