嵌套属性轨道错误 5.无法写入未知属性"address_id"



我在模型Patient上使用接受嵌套属性。我的表格我使用fields_for,用于连接与患者的地址字段。但是,对于我的字段出现在我的控制器Patients上的视图中,我在def new上有这个代码用于联接字段@ppatient.build_address,但这导致了这个错误。

我使用的是Rails 5.2.4.1。

can't write unknown attribute `address_id` Extracted source (around line #18):

def new
@patient = Patient.new
@patient.build_address   
end 

从关联开始是向后的。你想把外键放在地址表上。

rails g add_patient_to_addresses patient:references
rails db:migrate

然后像这样设置关联:

class Patient < ApplicationRecord
has_one :address
end
class Address < ApplicationRecord
belongs_to :patient
end

这不仅在语义上是正确的(地址是用户的属性,反之亦然(,而且如果需要,还可以将关联从一对一更改为一对多(例如,如果用户有不同的家庭和账单地址(。

最新更新