私のrails3.2アプリケーションには、次のポリモーフィックな関連付けを持つユーザーモデルと医師モデルがあります。
ユーザー
class User < ActiveRecord::Base
attr_accessible :authenticatable_id, :authenticatable_type, :email
belongs_to :authenticatable, polymorphic: true
end
医師
class Physician < ActiveRecord::Base
attr_accessible :name
has_one :user, as: :authenticatable
end
これらをコンソールでテストしたかったのですが、奇妙なことに遭遇しました。行うこと:
p = Physician.new
p.user.build
私に与えますNoMethodError: undefined method 'build' for nil:NilClass
-しかし、なぜ医師のユーザー属性はそうなるのnil
でしょうか?
不思議なことに、私が医師のモデルをhas_many :users
代わりに変更するhas_one :user
と、
p = Physician.new
p.users.build
すべてが正常に動作します。
has_one
アソシエーションを機能させるために何が欠けていますか?