ruby-on-rails - 通过 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 不会像这样自动处理删除所有关联记录吗?还是我做错了什么或遗漏了什么?
解决方案
我只是在控制器中添加了一个附加功能来解决这个问题,作为暂时的解决方法:
# called after update
def delete_all_associations_if_empty
classes = student_params[:classes]
if classes.nil? or classes.empty?
@student.classes = []
end
end
推荐阅读
- java - 可执行 JAR 文件不适合屏幕
- javascript - 用烧瓶后端反应路由器
- php - 无法声明类 ABC,因为该名称已在使用中
- java - 转换为 POJO 列表时,带有连接的查询的结果会丢失顺序
- php - 从 PHP 错误上传 S3 文件:“调用未定义函数 GuzzleHttp\Psr7\hash_init()”
- powershell - 如何显示将超过 1 天的文件从一个文件夹复制到另一个文件夹的进度?
- postgresql - 如果 Node js Express Js Sequelize Postgres 中的偏执为真,需要删除完整的行
- reactjs - 通过字符串初始化组件
- node.js - node.js异步和等待multer问题
- ssl - Kubernetes 证书管理器 ssl 错误验证 ACME 帐户