Chris Muench
Chris Muench

Reputation: 18328

accepts_nested_attributes_for building form

I am getting an error: Undefined method build for nil:NilClass when trying to build an empty child object for my 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
#

Upvotes: 0

Views: 1102

Answers (1)

Will Ayd
Will Ayd

Reputation: 7164

since the Patient belongs to the user you need to build the Patient from the user.

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

Patient.new is basically used to create a blank instance of a Patient that you can render on say a new form, but when posting to a create you need to build it from a user.

Upvotes: 1

Related Questions