ruby-on-rails - 在 Rails 5.2 中使用 Has_Many_Through 记录保存记录
问题描述
保存以下作业记录时出现“跨度无效”错误:
#job.rb
class Job < ApplicationRecord
has_many :workspans
has_many :spans, through: :workspans
end
我在 rails 5.0 中没有收到此错误,但在升级时,我无法关联跨度。
数据来自一个相当标准的 rails 表单,每个 span 都有一个复选框。
#new.html.erb
<%= Span.each do |span| %>
<%= check_box_tag "job[span_ids][]", span.id %>
<% end %>
发生了什么变化,我现在应该如何设置表单以将跨度与 @job 关联?
更新,细节
#jobs_controller
def create
@job = Job.new(job_params)
if @job.save
flash[:success] = "Job Saved"
redirect_to action: :index
else
flash[:alert] = "Job Not Saved"
render 'new'
end
end
解决方案
belongs_to
默认情况下需要从 Rails 5.2 开始。您需要提及optional: true
以消除错误。
相关公关:https ://github.com/rails/rails/pull/18937
Rails repo 上的相关问题:https ://github.com/rails/rails/issues/23960
推荐阅读
- reactjs - ReactJS 的引导程序
- powershell - 如何在 PowerShell 中解析类似 JSON 的结构?
- visual-studio-2019 - “添加项目数据源”选项在哪里?
- javascript - 将基于类的组件转换为未读取的功能组件输入查询
- office-js - 我可以使用 Outlook 加载项来保存电子邮件并更新用户 PC 上的文件吗
- node.js - 如何使用密码在 Angular 中生成 RSA 密钥对?
- amazon-emr - 带有 EMR addstep 的 aws 步进函数工作流
- javascript - 无法在 JavaScript 中使用我自己的 TypeScript 库
- grafana - 您可以在仪表板变量中使用 $__from 和 $__to 吗?
- selenium-webdriver - 使用 Selenium Java 在一个 for 循环中使用多个 List WebElement