Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 has_and_belongs_to_many creates checkboxes in view

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

like image 446
denisjacquemin Avatar asked Dec 04 '25 15:12

denisjacquemin


1 Answers

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.

like image 94
Max Williams Avatar answered Dec 07 '25 03:12

Max Williams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!