所以,我不确定如何设置我的关联。首先,我有一个用户模型(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
因此,我不确定用户模型应该如何与其他模型相关联。我的设计有缺陷吗?
感谢您帮助一个菜鸟。
答案 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
,设置这些不同类型用户之间的一对多关联的最佳方式是最小化重复。 },Nurse
和Therapist
首先,将这些模型之间的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:integer
,nurse_id:integer
和therapist_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