开发者

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 Compan开发者_开发百科y.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


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.


I have to agreed with @carpeliam a has_many :through should not be the default choice. A HABTM works fine and involves less code. It also does not restrict the use of ajax and does expose a origin_ids setter to which you can pass an array of ids. Therefore the screencast, whilst from 2007, still works with Rails 3. The other option if using simple_form is this:

= form.association :origins, :as => :check_boxes


Personally I'm not of the belief that has-many-through is always better, it really depends on your situation. Has-many-through is better if there is ANY possibility of your join model having attributes itself. It's more flexible to change. It removes the magic of some Rails conventions. If however you don't need has-many-through, then there's an old RailsCast for HABTM checkboxes that might come in handy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜