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 CA开发者_运维百科USES 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
#
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.
精彩评论