在 Rails 5.2 中保存有 Has_Many_Through 条记录

Saving a record with Has_Many_Through records in Rails 5.2

我在保存以下作业记录时遇到 "spans invalid" 错误:

#job.rb
class Job < ApplicationRecord
    has_many :workspans
    has_many :spans, through: :workspans
end

我在 rails 5.0 中没有遇到这个错误,但是在升级时,我无法关联跨度。

数据来自相当标准的 rails 表单,每个范围都有一个复选框。

#new.html.erb
<%= Span.each do |span| %>
  <%= check_box_tag "job[span_ids][]", span.id %>
<% end %>

发生了什么变化,我现在应该如何设置表单以将 span 与 @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

从Rails 5.2 默认需要belongs_to。您需要提及 optional: true 以消除错误。

相关公关:https://github.com/rails/rails/pull/18937

Rails 回购上的相关问题:https://github.com/rails/rails/issues/23960