我与DoctorProfile
和Insurance
有很多关系。我想从客户端应用程序的表单创建这些关联。我正在发送一个doctor_insurances_ids
数组并试图在一行中创建关联。是否可以发送回doctor_insurances
ID数组?如果是这样,那么在params中为大规模分配命名它的正确方法是什么?
我使用以下代码获得的错误是
ActiveRecord::UnknownAttributeError: unknown attribute 'doctor_insurances_ids' for DoctorProfile.
class DoctorProfile
has_many :doctor_insurances
accepts_nested_attributes_for :doctor_insurances # not sure if needed
class Insurance < ActiveRecord::Base
has_many :doctor_insurances
class DoctorInsurance < ActiveRecord::Base
# only fields are `doctor_profile_id` and `insurance_id`
belongs_to :doctor_profile
belongs_to :insurance
def create
params = {"first_name"=>"steve",
"last_name"=>"johanson",
"email"=>"steve@ymail.com",
"password_digest"=>"password",
"specialty_id"=>262,
"doctor_insurances_ids"=>["44", "47"]}
DoctorProfile.create(params)
end
答案 0 :(得分:1)
您没有在您的医生档案中加入doctor_insurance_id,因此您的DoctorProfile.create(params)行无效。你可以这样做:
def create
doctor = DoctorProfile.create(doctor_profile_params)
params["doctor_insurances_ids"].each do |x|
DoctorInsurance.create(doctor_profile_id: doctor.id, insurance_id: x)
end
end
def doctor_profile_params
params.require(:doctor_profile).permit(:first_name, :last_name, :email, :password_digest, :specialty_id)
end