我如何建立以下关系:用户、医生、患者、咨询、FoR ​​4 上的处方

How can I make a relationship betwen: User, Medic, Patient, Consultation, Prescription on RoR 4

我很难在医疗办公室的小项目中建立关系,我正在使用 Devise 进行用户登录,对我来说有意义的关系逻辑是这样的:

  1. 注册用户可以创建个人资料'Medic'
  2. 用户可以创建一个新的'patient'(应该与当前设计用户相关=> 'Medic')
  3. 新病人有新的'consultation'
  4. 并且咨询了'prescription'

所以,我通过以下方式设置我的模型:

class User < ActiveRecord::Base
  has_one :medic
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
end

class Medic < ActiveRecord::Base
  belongs_to :user
  has_many :patient
end

class Patient < ActiveRecord::Base
  belongs_to :medic
  has_many :consultum
end

class Consultum < ActiveRecord::Base
  belongs_to :patient
  has_one :prescription
end

class Prescription < ActiveRecord::Base
  belongs_to :consultum
end

对于脚手架我运行:

rails g scaffold Patient name last_name email phone references:medic

等等...

我觉得我缺少了一些东西,¿如何正确设置关系,以后不会遇到麻烦?,¿还有其他方法(最佳实践)吗?提前致谢。

我认为你把关系处理得很好,但如果你真的想阅读一些关于 rails 关系的好文档,请阅读:

http://www.toptal.com/ruby-on-rails/top-10-mistakes-that-rails-programmers-make

其中一个重要的事情是这个模型中的字段和类型,如果你选择正确它会更容易保持你的代码高效。

has_many 需要复数名称。另外我相信:

class Consultum < ActiveRecord::Base
  belongs_to :patient
  has_many :prescriptions
end

首先,您不需要单独的 Medic 模型关联到 User

如果您的 user 无论如何都将成为 medic,为什么不放弃 medic 模型而只使用 User?如果您更愿意将您的 User 模型称为 Medic,那就更好了。您必须更改应用中的一些引用:

#config/routes.rb
devise_for :medics

#app/models/medic.rb
class Medic < ActiveRecord::Base
   devise :database_authenticatable, :registerable,
       :recoverable, :rememberable, :trackable, :validatable

   has_one :profile
   before_create :build_profile
end

这使您可以访问 current_medic

如果您需要 个人资料,那就不同了:

#app/models/profile.rb
class Profile < ActiveRecord::Base
   belongs_to :medic
end

这将允许您调用 @medic.profile - 您不想让 "users" 模型知道的调用信息。

虽然这可能看起来离题,但它会极大地帮助您的联想。


#app/models/medic.rb
class Medic < ActiveRecord::Base
   has_many :consultations
   has_many :patients, through: :consultations
end

#app/model/consultation.rb
class Consultation < ActiveRecord::Base
   belongs_to :patient
   belongs_to :medic
   has_one :prescription
end

#app/models/patient.rb
class Patient < ActiveRecord::Base
   has_many :consultations
   has_many :medics, through: :consultations
end

#app/models/prescription.rb
class Prescription < ActiveRecord::Base
   belongs_to :consultation
end

-

检查:

Registered user can create a profile 'Medic'

只需使用current_medic

您的患者不需要是用户,只需手动添加即可。只需使用 Medic 而不是 User.

,您就可以避免让自己头疼不已

我的实现还为医生提供了个人资料:

current_medic.profile

Medic can create a new 'patient'

current_medic.patients.new ...

Patient have a new 'consultation'

@consultation = @patient.consultation.new ...
@consultation.medic = Medic.find ...

Consultation have a 'prescription'

@consultation.prescription