0

I'm still a big noob to rails so I hope someone can help!

I have two models, Companies and Contacts with a HABTM between them. Both have controllers in place for CRUD. What I would like to be able to do, for example, is on the Company view page, have a form to link an existing contact (maybe a dropdown) or create a new contact and link it to the Company. And vice versa. Not sure if this is possible?

Freddy Wetson
  • 456
  • 1
  • 4
  • 23

1 Answers1

1

If I am getting the question right, you want to create a has_and_belongs_to_many relationship between company and contact. so in your Company.rb add

has_and_belongs_to_many :contacts

and in your Contact.rb add

has_and_belongs_to_many :companies

Now for this relationship create a new table companies_contacts with two fields 'company_id' and 'contact_id'

In company controller inside show action

@contact = Contact.new

In show page of company add this:-

<%= form_for @contact,:url => contacts_path(:company_id=> @company.id) do |f|%>
  <%=f.label :name%>
  <%=f.text_field :name%>
  <%=f.button :submit%>
<%end%>

Now in the contact controller create action do like this:-

@contact = Contact.find_or_create_by_name(params[:contact][:name])
@contact.companies= Company.where(:id => params[:company_id])
@contact.save
Nikita Singh
  • 370
  • 3
  • 12
  • undefined method `contacts' for #<#:0xb0ce404> – Freddy Wetson Oct 08 '13 at 11:01
  • But what I would like to do is on the companies show page is have a dropdown of contacts to select from? – Freddy Wetson Oct 08 '13 at 11:02
  • Edited the answer <%= form_for @contact,:url => contacts_path(:company_id=> @company.id) do |f|%> :url should be contacts_path instead of contacts – Nikita Singh Oct 08 '13 at 11:21
  • for drop down you can use select tag inside a form tag like this <%= select_tag("company_ids", options_for_select(Company.all.collect{|u|[u.name,u.id]}),{:multiple=> true,:size =>3, :id => "companies"}) %> and then on submit call an appropriate action in companies controller and save the entries in companies_contacts table. – Nikita Singh Oct 08 '13 at 11:37