2015-06-27 61 views
1

我与DoctorProfileInsurance有多对多的关系。我想从客户端应用程序的表单创建这些关联。我发回一组doctor_insurances_ids并尝试在一行中创建关联。是否有可能发回一组doctor_insurances ID?如果是这样的话,在参数中将其命名为批量分配的正确方法是什么?Rails 4使用嵌套属性创建模型has_many

我用下面的代码得到的错误是

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"=>"[email protected]", 
"password_digest"=>"password", 
"specialty_id"=>262, 
"doctor_insurances_ids"=>["44", "47"]} 

    DoctorProfile.create(params) 

end 

回答

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 
+0

是的,这就是我现在的,但希望有一个更干净的方式:) – user2954587