首页 > 解决方案 > 在 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

标签: ruby-on-railsruby-on-rails-5.2

解决方案


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

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

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


推荐阅读