Nested checkboxes in Rails

試著忘記壹切 提交于 2021-02-08 08:58:01

问题


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 checkboxes are no longer checked???

here are the contents of my model files

# models
class Event < ActiveRecord::Base
  has_many :tables, dependent: :destroy
  has_many :people , through: :tickets
  has_many :tickets
  accepts_nested_attributes_for :tickets, allow_destroy: true
  accepts_nested_attributes_for :tables, allow_destroy: true
end

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?


回答1:


You can use http://apidock.com/rails/v4.0.2/ActionView/Helpers/FormOptionsHelper/collection_check_boxes

<%= f.collection_check_boxes(:people_ids, Person.all, :id, :name) do |person| %>
  <%= person.label { person.check_box } %>
<% end %>

It will persist data as well.



来源:https://stackoverflow.com/questions/38935467/nested-checkboxes-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!