views:

82

answers:

1

Hi,

Based on following models

class Company < ActiveRecord::Base
  has_and_belongs_to_many :origins
end

class Origin < ActiveRecord::Base
  has_and_belongs_to_many :companies
end

I want to have in my companies/_form a collection of checkboxes representing all origins.

Don't know if the Company.new(params[:company]) in companies_controller#create can create the association between company and the selected origins?

I'm running rails 3.0.0, what is the best way to achieve that?

thanks for your insights

+1  A: 

habtm isn't a popular choice these days, it's better to use has_many :through instead, with a proper join model in between. This will give you the method Company#origin_ids= which you can pass an array of origin ids to from your form, to set all the associated origins for @company. eg

<% current_origin_ids = @company.origin_ids %>
<% form_for @company do |f| %>
  <label>Name:<%= f.text_field :name %></label>
  <% Origin.all.each do |origin| %>
    <label><%= origin.name %>
      <%= check_box_tag "company[origin_ids][]", origin.id, current_origin_ids.include?(origin.id) %>
    </label>
  <% end %>
<% end %>

As an aside, using a proper join model, with corresponding controller, allows you to easily add/remove origins with AJAX, using create/delete calls to the join model's controller.

Max Williams
awesome, thanks
denisjacquemin