rails 多对多关联

模型

proofing.rb

has_many :proofing_material_maps
has_many :proofing_materials, through: :proofing_material_maps

proofing_material.rb

has_many :proofing_material_maps
has_many :proofings, through: :proofing_material_maps

proofing_material_map.rb

belongs_to :proofing
belongs_to :proofing_material

我使用的是simple_form

https://github.com/plataformatec/simple_form

Associations

To deal with associations, Simple Form can generate select inputs, a series of radios buttons or checkboxes. Lets see how it works: imagine you have a user model that belongs to a company and has_and_belongs_to_many roles. The structure would be something like:

class User < ActiveRecord::Base
  belongs_to :company
  has_and_belongs_to_many :roles
end

class Company < ActiveRecord::Base
  has_many :users
end

class Role < ActiveRecord::Base
  has_and_belongs_to_many :users
end

Now we have the user form:

<%= simple_form_for @user do |f| %>
  <%= f.input :name %>
  <%= f.association :company %>
  <%= f.association :roles %>
  <%= f.button :submit %>
<% end %>

Simple enough, right? This is going to render a :select input for choosing the :company, and another :select input with :multiple option for the :roles. You can, of course, change it to use radio buttons and checkboxes as well:

f.association :company, as: :radio_buttons
f.association :roles,   as: :check_boxes

The association helper just invokes input under the hood, so all options available to :select:radio_buttons and :check_boxes are also available to association. Additionally, you can specify the collection by hand, all together with the prompt:

f.association :company, collection: Company.active.order(:name), prompt: "Choose a Company"

In case you want to declare different labels and values:

f.association :company, label_method: :company_name, value_method: :id, include_blank: false

Please note that the association helper is currently only tested with Active Record. It currently does not work well with Mongoid and depending on the ORM you're using your mileage may vary.

多选我使用了select2

https://select2.org/

所以模板_from.html.erb

<%= f.association :proofing_materials, collection: proofing_materials_options, input_html: {class: 'ty-select2'}, label: '材质', prompt: '材质' %>

select2 使用prompt是没有效果的,需要在select2设置

$('.ty-select2').select2({
    placeholder: '请选择'
  })

保存

proofings_controller.rb

proofing_params = params.require(:proofing)
                                  .permit(
                                    :title,
                                    :drawing,
                                    :description,
                                    :proofing_material_ids => []
                                  )

 这里需要记住使用proofing_material_ids获取而不是proofing_materials

@proofing = Proofing.create!(proofing_params)
@proofing.save

猜你喜欢

转载自blog.csdn.net/tang05709/article/details/87633111