Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 接受建筑窗体的\u嵌套\u属性\u_Ruby On Rails_Ruby On Rails 3 - Fatal编程技术网

Ruby on rails 接受建筑窗体的\u嵌套\u属性\u

Ruby on rails 接受建筑窗体的\u嵌套\u属性\u,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,尝试为窗体生成空的子对象时,我遇到一个错误:nil:NilClass的未定义方法build class PatientsController < ApplicationController def index end def new @patient = Patient.new # THIS CAUSES AN ERROR (undefined method `build' for nil:NilClass) @patient.user.build

尝试为窗体生成空的子对象时,我遇到一个错误:nil:NilClass的未定义方法build

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
#
class PatientsController
由于患者属于用户,因此需要根据用户构建患者

@user.patients.build(params[:patient])

Patient.new基本上用于创建患者的空白实例,您可以在新表单上呈现该实例,但在发布到create时,您需要从用户处构建该实例。

我正在尝试创建一个新表单,并且有一个空的Patient对象。许多消息来源称使用build。该用户有一名患者,该患者属于某个用户。表单将包含一些需要跨两个表保存的患者信息和用户信息。实际创建对象并将其保存在数据库中时,将使用build。要创建一个允许发布新实例的表单,只需执行@patient=patient.new。我想最重要的是不要将这两者混为一谈。很难具体告诉您如何实现这一点,但通常您希望为新患者创建一个表单,通过patient.new在控制器中创建一个实例变量,并将其传递给表单,然后,当您提交表单时,您需要能够创建用户对象(通过会话或通过在表单中传递:user\u id),您可以从中构建如上所示的患者。我之前也没有提到这一点,但用户模型应该接受患者模型的\u嵌套\u属性。患者属于用户模型,这意味着它是用户的嵌套属性。你有那个backwards我把它换了过来,试着去做:@patient=User.new@patient.patient.build,但我还是得到了零错误