2017-10-12 44 views
0

我有一個單用戶模型中定義多個用戶類型:配置文件不被外鍵的相關模型創建

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

臨牀醫生的用戶都有一個使用after_create自動創建一個臨牀醫生的個人資料,而且我打算將clinician_profile id存儲在用戶表中。出於某種原因,在創建臨牀醫生簡檔時,所有用戶(包括臨牀醫生用戶)的clinicalician_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 

用戶表模式:

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,如果::臨牀醫師? – mike9182

+0

嘗試顯式創建一個方法'def create_clinician_profile; self.clinician_profile.create !;結束' – max

回答

1

此處不應使用類方法來對實例對象進行操作。

你可以使用一個回調塊來代替:

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

此外,該協會被定義爲belong_to所以父對象也可以創建這個關聯,但是這只是個人意見。

相關問題