2015-06-27 97 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