Reputation: 14275
In my rails 3.2 application I have a User model and a Physician model with the following polymorphic associations:
User
class User < ActiveRecord::Base
attr_accessible :authenticatable_id, :authenticatable_type, :email
belongs_to :authenticatable, polymorphic: true
end
Physician
class Physician < ActiveRecord::Base
attr_accessible :name
has_one :user, as: :authenticatable
end
I wanted to test these out in the console and encountered a strange thing. Doing:
p = Physician.new
p.user.build
gives me NoMethodError: undefined method 'build' for nil:NilClass
- but why would the physician's user attribute be nil
?
Strangely, when I change the physician model to has_many :users
instead of has_one :user
and do
p = Physician.new
p.users.build
everything works fine.
What am I missing to get the has_one
association to work?
Upvotes: 0
Views: 179
Reputation: 1776
You probably should do p.build_user
since has_one
doesn't add association.build
method. You can also check apidock about methods has_one and has_many 'injects' into your model.
Upvotes: 1
Reputation: 37905
It is not entirely clear to me, but it seems that your are creating a Physician
that is also a User
. So it is able to make use of the features a User
provides.
Your implementation creates two objects one Physician
and oneUser
, but when strictly looking at the situation, both are the same Physician/User.
So you should let Physician
inherit from User
:
class Physician < User
and remove the polymorphic relation between Physician
and User
.
Upvotes: 0