Rails ActiveRecord与一对多的关联

时间:2017-10-03 00:31:47

标签: ruby-on-rails activerecord associations

所以,我不确定如何设置我的关联。首先,我有一个用户模型(Devise),它有电子邮件和密码。

class User < AR::Base
end

之后,我有多种类型的用户模型,其中包含有关用户的更多详细信息:

class Doctor < AR::Base
  belongs_to: User
end

class Nurse < AR::Base
  belongs_to: User
end

class Therapist < AR::Base
  belongs_to: User
end

因此,我不确定用户模型应该如何与其他模型相关联。我的设计有缺陷吗?

感谢您帮助一个菜鸟。

3 个答案:

答案 0 :(得分:2)

实现您要实现的目标的最简单方法是在用户上添加一列来分配角色。所以你可以调用这样的方法:

User.add_role(:doctor)
User.has_role?(:doctor)

你可以使用这个gem https://github.com/mcrowe/roleable

来做到这一点

实现它的另一种方法是使用ActiveRecord Enum: http://api.rubyonrails.org/v5.1/classes/ActiveRecord/Enum.html实现如下:

User.role # => :doctor
User.doctor? # => true
User.therapist! # => true
User.role # => :therapist

我个人更喜欢使用枚举。

一种复杂的方法是使用多态。在哪里可以将User作为多态模型。这篇博文详细解释了它。 https://robots.thoughtbot.com/using-polymorphism-to-make-a-better-activity-feed-in-rails

答案 1 :(得分:1)

Rails数据库关联文档Link

将这些has_many添加到user.rb

#user.rb
has_many :doctor 
has_many :nurse
has_many :therapist 

并且您需要将user_id添加到医生,护士和治疗师。

如:

rails g migration add_user_id_to_nurses user_id:integer
rails g migration add_user_id_to_doctors user_id:integer
rails g migration add_user_id_to_therapits user_id:integer

最后不要忘记rake db:migrate

答案 2 :(得分:1)

通过将User设置为belong_to这些其他模型Doctor,设置这些不同类型用户之间的一对多关联的最佳方式是最小化重复。 },NurseTherapist

首先,将这些模型之间的has_many关联设置为User模型

# app/models/doctor.rb
class Doctor < ActiveRecord::Base
  has_many: :users
end

# app/models/nurse.rb
class Nurse < ActiveRecord::Base
  has_many: :users
end

# app/models/therapist.rb
class Therapist < ActiveRecord::Base
  has_many: :users
end    

然后,添加迁移以将doctor_id:integernurse_id:integertherapist_id:integer添加到users表。

然后,设置belongs_to与其他ActiveRecord模型的关联。

# app/models/user.rb
class User < ActiveRecord::Base
  belongs_to: :doctor
  belongs_to: :nurse
  belongs_to: :therapist
end

使用此设置,您可以按如下方式访问这些模型的ActiveRecord数据:

# get doctor associated to User.last
User.last.doctor
# get all the users who are patients of Doctor.last
Doctor.last.users

# get the nurse associated to User.last
User.last.nurse
# get all the users who are patients of Nurse.last
Nurse.last.users