mardi 13 novembre 2018

Create multiple new records from checkboxes in form using nested attributes in Rails

I'm trying to come up with a contact form that creates a contact record and potentially multiple location records, if multiple locations are checked in a list of checkboxes. I thought of having all location records created and then destroyed, if they aren't checked. I don't think that's optimal though.

I'm using many to many relationships in the models.

This is what they look like at the moment:

contact.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

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

Does anyone how to make it work properly? I'm working on Ruby 2.5.1 and Rails 5.2.1.

Thanks a lot.




Aucun commentaire:

Enregistrer un commentaire