在相关模型中创建没有外键的配置文件

时间:2017-10-12 15:30:59

标签: ruby-on-rails foreign-keys

我在单个用户模型中定义了多种用户类型:

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

临床医师用户每个人都有一个使用after_create自动创建的临床医师简介,我打算将clinician_profile id存储在users表中。出于某种原因,当创建临床医生简档时,临床医师_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

class 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"

1 个答案:

答案 0 :(得分:1)

此处不应使用类方法来操作实例对象。

您可以使用回调块:

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

此外,关联被定义为belongs_to,因此父对象也可以创建关联,但这只是个人意见。