Rails 批量分配 has_and_belongs_to_many

Rails Mass Assign has_and_belongs_to_many

当我尝试在 Rails 5:

中批量分配 HABTM 关系时出现此错误

*** ActiveRecord::RecordNotFound Exception: Couldn't find Job with ID=6 for Profile with ID=

class Profile < ApplicationRecord
  has_and_belongs_to_many :jobs
  accepts_nested_attributes_for :jobs
end

class Job < ApplicationRecord
  has_and_belongs_to_many :profiles
end

class ProfilesController < ApplicationController

  def create
    @profile = Profile.new(profile_params)
  end

  private

    def profile_params
      params.require(:profile).permit(
        :name,
        :email,
        :jobs_attributes: [:id]
      )
    end
end

=form_for @profile do |f|
  =f.fields_for :jobs do |j|
    =j.select :id, options_for_select([[1, "Job 1", ...]])

问题是 accepts_nested_attributes_for 是一种更新关联对象(已经链接或正在创建的对象)属性的方法。你可以把它想象成这样:

params[:jobs_attributes].each do |job_attributes|
  @profile.jobs.find(job_attributes[:id]).attributes = job_attributes
end

除了作业随后与父对象的 after-save 中的新属性一起保存。

这不是你想要的。事实上,你根本不需要 accepts_nested_attributes

相反,将视图中的属性更改为 job_ids,就好像它是 profile 的属性一样,如下所示:

=form_for @profile do |f|
  =j.select :job_ids, options_for_select([[1, "Job 1", ...]])

这将有效地调用 profile.job_ids = [1,2,3],这将产生您正在寻找的效果。