我有以下问题,
一个用户可以拥有多个专业(超过10个)。例如,一个用户可以是医生,老师和N。每个专业都有其自己的属性。
我可以做的,Doctor属称到用户,但是如果我想知道这个用户的所有职业,我将不得不检查用户表的每一行。
我创建了以下代码
class User < ApplicationRecord
has_many :jobables
end
class Job < ApplicationRecord
belongs_to :user
belongs_to :jobable
end
class Jobable < ApplicationRecord
has_one :job
end
class Medic < Jobable
end
class Programmer < Jobable
end
但是我不知道那是否是最好的答案
最佳答案
我认为做这样的事情会容易得多:
class User < ApplicationRecord
has_many :user_professions
has_many :professions, through: :user_professions
end
# == Schema Information
#
# Table name: professions
#
# id :integer not null, primary key
# name :string
# created_at :datetime not null
# updated_at :datetime not null
#
class Profession < ApplicationRecord
has_many :user_professions
has_many :users, through: :user_professions
end
class UserProfession < ApplicationRecord
belongs_to :user
belongs_to :profession
end
然后,您可以创建逻辑以确保仅将
Profession
分配给User
一次。然后,您可以简单地执行以下操作:
@user.professions
并获取所有
Profession
的User
。您也可以这样做:
@profession.users
并获取属于
User
的所有Profession
。根据您对问题的编辑,您可以执行以下操作:
class UserProfession < ApplicationRecord
belongs_to :user
belongs_to :profession
belongs_to :profession_detail, polymorphic: true
end
在这种情况下,您可能会遇到以下情况:
class DoctorDetail < ApplicationRecord
end
您可以执行以下操作:
@user.professional_detail_for(:doctor)
当然,您需要在
professional_detail_for
模型上实现User
方法,该方法可能类似于:class User < ApplicationRecord
has_many :user_professions
has_many :professions, through: :user_professions
def professional_detail_for(profession_type)
user_profession_for(profession_for(profession_type)).try(:profession_detail)
end
private
def profession_for(profession_type)
Profession.find_by(name: profession_type.to_s)
end
def user_profession_for(profession)
user_professions.find_by(profession: profession)
end
end
这有点粗糙,但我想您会明白的。
关于ruby-on-rails - 通过Ruby on Rails中的关联实现多态has_many,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50223669/