0

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?

tereško
  • 58,060
  • 25
  • 98
  • 150
Dennis Hackethal
  • 13,662
  • 12
  • 66
  • 115

2 Answers2

1

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.

Vadym Chumel
  • 1,766
  • 13
  • 20
0

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.

Veger
  • 37,240
  • 11
  • 105
  • 116
  • Thanks for your answer! I am using Devise's user model and simply need different user roles. For example, there is not only a physician, but later there might also be a pharmacy, etc - but they are all users. So I think the polymorphic association is the right approach, I just need to get the association working... Any ideas? – Dennis Hackethal Jan 27 '13 at 13:15
  • The roles can implemented using the inheritance. For example `class Pharmacy < User` is also valid. Unless you will get users with multiple roles at the same time... – Veger Jan 27 '13 at 13:16