【发布时间】:2019-04-16 20:10:07
【问题描述】:
如果在复选框列表中选中多个位置,我正在尝试创建一个联系人表单,该表单创建一个联系人记录和可能的多个位置记录。如果不检查所有位置记录,我想创建然后销毁它们。不过我认为这不是最佳选择。
我在模型中使用多对多关系。
这就是他们现在的样子:
联系人.rb
class Contact < ApplicationRecord
has_many :contact_locations, dependent: :destroy
has_many :locations, through: :contact_locations
accepts_nested_attributes_for :contact_locations, allow_destroy: true, reject_if: :empty_location?
private
def empty_location?(att)
att['location_id'].blank?
end
end
位置.rb
class Location < ApplicationRecord
has_many :locations, dependent: :destroy
has_many :contacts, :through => :contact_locations
has_many :contact_locations
end
contact_location.rb
class ContactLocation < ApplicationRecord
belongs_to :location
belongs_to :contact
end
contacts_controller.rb
def new
@contact = Contact.new
@locations = Location.all
4.times {@contact.contact_locations.new}
end
private
def contact_params
params.require(:contact).permit(:name, :phone, ..., contact_locations_attributes: [:location_ids])
end
new.html.rb
<%= form_with model: @contact do |f| %>
...
<%= @locations.each do |location| %>
<%= f.fields_for :contact_locations do |l| %>
<%= l.check_box :location_id, {}, location.id, nil %><%= l.label location.name %>
<% end %>
<% end %>
...
<% end %>
有没有人可以让它正常工作? 我正在开发 Ruby 2.5.1 和 Rails 5.2.1。
非常感谢。
【问题讨论】:
标签: ruby-on-rails checkbox nested-attributes