samedi 13 août 2016

Nested checkboxes in Rails

I'm trying to create an event app where each event has multiple tables and each table has multiple people sitting at a table the event has multiple tickets which map the people to the tables that they are sitting at -> in order to achieve this I have created a checkbox nested in the fields_for :tables (which is in turn in the event form) I presume something is wrong with either the strong parameters or the form itself but I have not been able to find any information that provides a solution to the problem.After checking the checkboxes in the form indicating which people are going to be sitting at this table and submitting the form and returning to the form I find that the the checkboxes are no longer checked???

here are the contents of my model files

 class Table < ActiveRecord::Base
   belongs_to :event
   has_many :tickets
   has_many :people, through: :tickets
 end  

 class Ticket < ActiveRecord::Base
   belongs_to :table
   belongs_to :person
 end

class Person < ActiveRecord::Base
   has_many :tickets
   has_many :tables, through: :tickets
end

Here is the form with parts omitted for brevity.

<%= form_for(@event) do |f| %>
  ...
  <%= f.fields_for :tables do |builder| %>
    <%= render 'table_field', f: builder %>
  <% end %>
  <%= link_to_add_fields "Add Table", f, :tables %>    
  ...
<% end %>

And here is the checkbox list I have implemented within the table_field.

<% Person.all.each do |person| %>
            <div class="field">     
              <%= check_box_tag "table[people_ids][]", person.id, f.object.people.include?(person) %> <%= f.label [person.first_name, person.last_name].join(" ")  %>
            </div>
          <% end %>

this is the event_params

 def event_params
      params.require(:event).permit(:name, :description, :start, :end, :latitude, :longitude, :address, :data, :people_ids => [], tables_attributes: [:id, :number, :size, :people_ids => []]).tap do |whitelisted|
    whitelisted[:data] = params[:event][:data]
  end

How do I get the checkboxes to be persistently checked in this form?




Aucun commentaire:

Enregistrer un commentaire