嵌套形式的 HABTM 复选框 [英] HABTM checkbox in a nested form

查看:48
本文介绍了嵌套形式的 HABTM 复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以嵌套形式实现 HABTM 复选框.

I am trying to implement a HABTM checkbox in a nested form.

目前,我有 3 个模型.主题、课程和小组.协会如下:每个科目都有很多课.每节课都有并属于多个组.

Currently, I have 3 models. Subject, lesson and groups. The associations are as follows: Each subject has many lessons. Each lesson has and belongs to many groups.

现在,我正在尝试在一个创建和编辑表单上实现它们.这样一来,课程就嵌套在主题中,并且每节课都有一组用于实现 HABTM 关系的组复选框.

Right now, I am trying to implement them all on a single creation and edit form. Such that a lesson is nested in the subject and for each lesson there is a list of group check boxes to implement the HABTM relationship.

我在实施 HABTM 关系时遇到了麻烦,因为每个科目有很多课程,我不确定如何区分不同的课程.

I am facing trouble implementing the HABTM relationship as there are many lessons per subjects and I am not sure how I could distinguish between the different lessons.

进一步详细说明,我可以使嵌套表单正常工作,但无法将 HABTM 复选框保存到正确的课程中.以下代码示例是我的 HABTM 复选框实现.

To elaborate further, I am able to get the nested form working but I can't get the HABTM checkboxes to save to the right lessons. The following code sample is my HABTM checkbox implementation.

  <% Group.all.each do |group|%>
      <%= check_box_tag "subject[lessons_attributes[0]][group_ids][]", group.id, f.object.groups.include?(group) %>
      <%= group.group_index %>
  <%end%>

目前,我已使用subject[lessons_attributes[0]][group_ids][]"这一行将其保存到第一课.

Currently, I have saved it to the first lesson using this line "subject[lessons_attributes[0]][group_ids][]".

但是,课程的数量各不相同,我不太确定如何确定课程编号",即subject[lessons_attributes[0]]][group_ids][]".这样我就可以将小组保存到正确的课程中.

However, the number of lessons vary and I am not too sure how I could determine the lesson "number", i.e. the bolded 0 in "subject[lessons_attributes[0]][group_ids][]". Such that I could save the groups to the correct lesson.

任何建议将不胜感激.

推荐答案

最佳实践是预先构建(一些)关于主题的课程对象(即 form.object),然后迭代它们以获得每个课程领域.如果您使用 simple_formformtastic,通过复选框选择集合很容易:

the best practice is to prebuild (a few) lesson object on the subject (that is the form.object), then you iterate over them to have per-lesson fields. if you use simple_form or formtastic, collection select via checkboxes is easy:

<% form_for @subject do |form| %>
  ....
  <% form.fields_for :lessons do |lesson_form| %>
    ...
    <% lesson_form.input :group_ids, :as => :check_boxes %>

如果您想使用 check_box_tag,您应该使用索引遍历课程并将索引替换为您的复选框名称:

if you wanna use check_box_tag, you should iterate through lessons with an index and substitute the index in your checkbox name:

<% form_for @subject do |form| %>
  ....
  <% @subject.lessons.each_with_index do |l, i| %>
     <% Group.all.each do |group|%>
        <%= check_box_tag "subject[lessons_attributes[#{i}]][group_ids][]", group.id, l.groups.include?(group) %>
        <%= group.group_index %>
     <% end %>

这篇关于嵌套形式的 HABTM 复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆