【问题标题】:Nested checkboxes in RailsRails 中的嵌套复选框
【发布时间】:2016-12-20 12:01:30
【问题描述】:

我正在尝试创建一个活动应用程序,其中每个活动有多个桌子,每个桌子有多个人坐在一张桌子上,活动有多张票,将人们映射到他们坐的桌子 -> 以便实现这一点我创建了一个嵌套在 fields_for :tables 中的复选框(这又在事件表单中)我认为强参数或表单本身有问题,但我无法找到任何提供的信息问题的解决方案。在检查了表单中的复选框,表明哪些人将坐在这张桌子上并提交表单并返回表单后,我发现复选框不再被选中???

这是我的模型文件的内容

# 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

为简洁起见,此处省略了部分表格。

<%= 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 %>

这是我在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 %>

这是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

如何让复选框在此表单中持续选中?

【问题讨论】:

    标签: ruby-on-rails checkbox nested-forms checkboxlist strong-parameters


    【解决方案1】:

    您可以使用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 %>
    

    它也会持久化数据。

    【讨论】:

    • 我得到错误 undefined method `people_ids' for #<0x94f7b38>
    • &lt;&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 2013-06-26
    • 2011-02-20
    • 2013-10-31
    • 1970-01-01
    相关资源
    最近更新 更多