Rails 3 has_and_belongs_to_many creates checkboxes in sight

Based on the 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/_formset of flags representing all the origin.

Not sure whether Company.new(params[:company])to companies_controller#createcreate a link between the company and the selected source?

I am running rails 3.0.0, what is the best way to achieve this?

thanks for your ideas

+3
source share
3 answers

habtm , has_many: , . Company # origin_ids =, , @company. ,

<% 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 %>

, , / AJAX, create/delete .

+9

@carpeliam a has_many :through . HABTM . ajax origin_ids, . screencast, 2007 , - Rails 3. , simple_form:

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

Personally, I am not of the opinion that there is much-through is always better, it really depends on your situation. Has-many-through is better if there is ANY possibility of your joining model with the attributes themselves. It is more flexible for change. It removes the magic of some Rails conventions. If, however, you do not need a multi-pass-through, then you may need the old RailsCast for the HABTM flags .

+2
source

Source: https://habr.com/ru/post/1765973/


All Articles