使用accepts_nested_attributes_for创建表单

我有2个型号,一个是用户和病人。 用户HAS_ONE患者和患者BELONGS_TO用户。

class Patient < ActiveRecord::Base belongs_to :user accepts_nested_attributes_for :user attr_accessible :user_id, :user_attributes end # == Schema Information # # Table name: patients # # id :integer not null, primary key # user_id :integer # insurance :string(255) # created_at :datetime # updated_at :datetime # class User < ActiveRecord::Base has_one :patient attr_accessible :username, :password, :active, :disabled, :first_name, :last_name, :address_1, :address_2, :city, :state, :postcode, :phone, :cell, :email attr_accessor :password end # == Schema Information # # Table name: users # # id :integer not null, primary key # username :string(255) # encrypted_password :string(255) # salt :string(255) # active :boolean # disabled :boolean # last_login :time # first_name :string(255) # last_name :string(255) # address_1 :string(255) # address_2 :string(255) # city :string(255) # state :string(255) # postcode :string(255) # phone :string(255) # cell :string(255) # email :string(255) # created_at :datetime # updated_at :datetime # 

在我的病人控制器中,我正在尝试创建一个新的患者表格。

 class PatientsController < ApplicationController def new @patient = Patient.new end end 

在我的视图中(new.html.erb)

   
*: "TextField" %>
...

表单显示为空白,提交按钮没有为user_fields生成标记

我被告知我做错了,因为患者有accept_nested_attributes_for:用户,应该是用户在我的系统中嵌套属性BUT我想使用资源模型,以便分别处理患者和其他用户类型。

示例数据库表:

用户:id | first_name | last_name …等

患者:id | user_id |保险

除非我弄错了,否则你在调用fields_for时没有user 。 在您可以执行fields_for之前,您需要拥有一个可用于构建表单的用户实例,就像您对@patientpatient_form

您最好的选择是根据您的@patient在您的控制器中构建User ,然后您将在视图中访问该用户。

尝试使用等号的<%= patient_form.fields_for ? 我知道有一段关于“块状助手被弃用”的警告信息。

Jeff Casimir和theIV的答案是正确的,但你需要同时做到这两点。 即,将patient_form.fields_for块修复为用户<%= ,并在控制器中为患者构建User对象,如:

 def new @patient = Patient.new @patient.user = User.new end