0
我收到一个错误:当我试图为我的窗体构建一个空的子对象时,nil:NilClass未定义的方法构建。accepted_nested_attributes_for building form
class PatientsController < ApplicationController
def index
end
def new
@patient = Patient.new
# THIS CAUSES AN ERROR (undefined method `build' for nil:NilClass)
@patient.user.build
end
end
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
# created_at :datetime
# updated_at :datetime
#
我正在尝试创建一个新窗体并且有一个空的病人对象。许多消息来源表示使用构建。用户拥有一位患者,并且该患者属于用户。表格中将有一些患者信息和用户信息需要保存在两张表格中。 – 2011-02-23 12:50:34
构建用于实际创建对象以将其保存在数据库中时。只需要一个表单,它允许您发布一个新实例,您只需要执行@patient = Patient.new。我想最重要的是不要混淆和匹配这两个 – 2011-02-23 12:57:02
它很难告诉你具体如何实现,但通常你会想为新患者创建一个表单,通过Patient.new在控制器中创建一个实例变量你传递给表单,然后当你提交表单时,你需要能够创建用户对象(可以通过会话或通过传递:表单中的user_id),从中可以构建患者,如上所示。 – 2011-02-23 13:04:34