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?