當我嘗試在 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", ...]])
uj5u.com熱心網友回復:
問題在于這accepts_nested_attributes_for是一種更新關聯物件(已鏈接或您正在創建的物件)上的屬性的方法。你可以把它想象成這樣:
params[:jobs_attributes].each do |job_attributes|
@profile.jobs.find(job_attributes[:id]).attributes = job_attributes
end
除了隨后在父物件的后保存中使用新屬性保存作業。
這不是你想要的。事實上,你根本不需要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]which 將產生您正在尋找的效果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/444947.html
