I am developing a Rails 3.2 application with the following models:
class User < ActiveRecord::Base
# Associations
belongs_to :authenticatable, polymorphic: true
# Validations
validates :authenticatable, presence: true # this is the critical line
end
class Physician < ActiveRecord::Base
attr_accessible :user_attributes
# Associations
has_one :user, as: :authenticatable
accepts_nested_attributes_for :user
end
What I am trying to do is validate whether a user always has an authenticatable parent. This works fine in itself, but in my form the user model complains that the authenticatable is not present.
I am using the following controller to show a form for a new physician which accepts nested attributes for the user:
def new
@physician = Physician.new
@physician.build_user
respond_to do |format|
format.html # new.html.erb
format.json { render json: @physician }
end
end
And this is my create method:
def create
@physician = Physician.new(params[:physician])
respond_to do |format|
if @physician.save
format.html { redirect_to @physician, notice: 'Physician was successfully created.' }
format.json { render json: @physician, status: :created, location: @physician }
else
format.html { render action: "new" }
format.json { render json: @physician.errors, status: :unprocessable_entity }
end
end
end
On submitting the form, it says that the user's authenticatable must not be empty. However, the authenticatable_id and authenticatable_type should be assigned as soon as @physician
is saved. It works fine if I use the same form to edit a physician and its user, since then the id and type are assigned.
What am I doing wrong here?