2017-10-12 4 views
0

を作成されている私は、単一のユーザー・モデルで定義された複数のユーザータイプを持っている:プロファイルは、関連するモデルで外部キーなしで

enum role: { staff: 0, clinician: 1, admin: 2 } 

臨床医ユーザーごとに自動的にafter_createを使用して作成された臨床医のプロファイルを持っている、と私は意図していますclinician_profile idをusers表に保管します。何らかの理由で、臨床医プロファイルが作成されると、clinician_profile_idは、臨床医ユーザを含むすべてのユーザのためにユーザテーブル上でヌルのままである。どうすれば修正できますか?

モジュールClinicianUser

extend ActiveSupport::Concern 

    included do 
    belongs_to :clinician_profile 
    has_many :lists 
    has_many :universities, through: :lists 
    has_many :dispatches 
    has_many :referral_requests, through: :dispatches 
    after_create :create_clinician_profile, if: :clinician? 
    belongs_to :market 
    validates :market_id, presence: true, if: :clinician? 
    end 

    class_methods do 
    def create_clinician_profile 
     self.clinician_profile.create! 
    end 

    end 
end 

クラスClinicianProfile < ApplicationRecord

has_one :user, -> { where role: :clinician } 
end 

Usersテーブルスキーマ:

create_table "users", force: :cascade do |t| 
    t.string "email" 
    t.datetime "created_at",          null: false 
    t.datetime "updated_at",          null: false 
    t.string "password_digest" 
    t.string "remember_digest" 
    t.string "activation_digest" 
    t.boolean "activated",      default: false 
    t.datetime "activated_at" 
    t.string "reset_digest" 
    t.datetime "reset_sent_at" 
    t.string "encrypted_password", limit: 128 
    t.string "confirmation_token", limit: 128 
    t.string "remember_token",  limit: 128 
    t.datetime "confirmed_at" 
    t.integer "role",        default: 0 
    t.string "first_name" 
    t.string "last_name" 
    t.integer "university_id" 
    t.boolean "approved",       default: false 
    t.integer "market_id" 
    t.integer "clinician_profile_id" 
    t.index ["clinician_profile_id"], name: "index_users_on_clinician_profile_id" 
    t.index ["email"], name: "index_users_on_email", unique: true 
    t.index ["market_id"], name: "index_users_on_market_id" 
    t.index ["remember_token"], name: "index_users_on_remember_token" 
+0

'create_clinician_profile'メソッドを追加できますか? – max

+0

明示的な方法はありません - 現在、臨床家の懸念事項モジュールでこの行だけに処理されています:after_create:create_clinician_profile if::clinician? – mike9182

+0

メソッド 'def create_clinician_profile;を明示的に作成してみてください。 self.clinician_profile.create !; end' – max

答えて

1

ここではクラスメソッドをインスタンスオブジェクトの操作に使用しないでください。

あなたが代わりにコールバックブロックを使用することができます。親オブジェクトがあまりにも関連付けを作成できるように

after_create do |user| 
    ClinicianProfile.create(user: user) if clinician? 
end 

はさらに、関連付けがbelong_toとして定義されていますが、それは単なる個人的な意見です。

関連する問題