rails active record relationship ...继承?

时间:2017-10-02 21:41:32

标签: ruby-on-rails rails-activerecord

我有多个用户角色:

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

员工用户创建患者记录并属于大学。

员工关注

require 'active_support/concern'

module StaffUser
  extend ActiveSupport::Concern

  included do
    belongs_to :university
    has_many :patients
    has_many :referral_requests
    validates :university_id, presence: true, if: :staff?
  end

患者模型

  class Patient < ApplicationRecord

  belongs_to :user, -> { where role: :staff }

  belongs_to :staff_clinician, class_name: 'User', foreign_key: 'staff_clinician_id'
    end

大学模式

class University < ApplicationRecord
  has_many :staffs

表中的第一个用户是员工用户,因此在控制台中我可以执行类似User.first.patients.count的操作来获取该员工用户创建的所有患者的计数。我希望能够做像University.first.patients.count这样的事情,但是当我尝试时我得到这个错误:

NoMethodError: undefined method `patients' for #<University:0x007f8dc9444b30>

我是否需要在Patient模型和University模型之间明确创建belongs_to has_many关系,并将university_id放入我的Patient表中以便能够返回值?换句话说,是否可以从属于大学的员工用户推断出由员工用户创建的任何患者也属于该大学,或者没有?

谢谢!

0 个答案:

没有答案