首页 > 解决方案 > 通过 rails 表单删除所有 ActiveRecord Join 关联。(添加和修改工作正常)

问题描述

所以我想我已经缩小了如何通过表单创建/修改关联的范围。但是,我似乎无法通过相同的方法删除所有关联,因为提交的参数包含一个空白数组(表单中没有选择任何内容)。当数组为空时,Rails什么都不做,而是删除所有关联记录。

所以这是我的应用程序的一个例子。这里有两个模型:

#app/models/student.rb
class Student < ApplicationRecord
    has_and_belongs_to_many :classes
end

#app/models/class.rb
class Class < ApplicationRecord
    has_and_belongs_to_many :students
end

现在假设我的表格适用于Student

  <%= form_with(model: @student, local: true) do |form| %>
    <table class="table table-striped table-bordered table-hover student-datatable">
    <thead>
        <tr>
            <th><%= check_box_tag "student_header_checkbox", 0, false %></th>
            <th>Class Name</th>
        </tr>
    </thead>
    <tbody>
        <% @classes.each do |class| %>
        <tr>
            <td><%= check_box_tag "student[class_ids][]", class.id, is_student_part_of_class(class) %></td>
            <td><%= class.name %></td>
        </tr>
        <% end %>
    </tbody>
</table>
  </div>
  <div class="modal-footer">
      <button type="submit" class="btn btn-success btn-sm">
        <i class='fa fa-save'></i> Save changes
      </button>
  </div>
  <% end %>

现在在我的Student控制器中,我允许class_ids在底部执行此操作:

#app/controllers/students.rb
def student_params
  params.require(:student).permit(:class_ids => [])
end

好的,一切都很好。当用户选择许多类时,这些类Student作为数组传递给控制器​​。如果选择了类,则创建适当的关联记录,现在学生“has_and_belongs_to_many”类。

现在问题来了

假设您向该学生添加了多个课程,如果删除所有课程,则基本上没有数组传递给控制器​​;因此,控制器不会删除与该学生关联的所有课程。

如果您通过添加一个类、删除一个类等来修改选择,除了取消选择 ALL classes 之外,那么一切正常。

rails 不会像这样自动处理删除所有关联记录吗?还是我做错了什么或遗漏了什么?

标签: ruby-on-rails

解决方案


我只是在控制器中添加了一个附加功能来解决这个问题,作为暂时的解决方法:

# called after update
def delete_all_associations_if_empty
   classes = student_params[:classes]
   if classes.nil? or classes.empty?
      @student.classes = []
   end
end

推荐阅读