基于 table in rails 的一个属性的 2 个不同模型
2 different model based on one attribute of a table in rails
假设我只想为 rails.but ruby 中的用户制作一个 table 我想根据用户的角色再制作 2 个模型。这样我就可以在它们之间使用另一个多对多关系。
class Patient < User
has_many :appointments
has_many :physicians, through: :appointments
end
class Physician < User
has_many :appointments
has_many :physicians, through: :appointments
end
class User < ApplicationRecord
end
class Appointment < ApplicationRecord
belongs_to :physician
belongs_to :patient
end
设置约会关联时需要手动指定外键列:
class Physician < User
has_many :appointments, foreign_key: :physician_id
has_many :patients, through: :appointments
end
class Patient < User
has_many :appointments, foreign_key: :patient_id
has_many :physicians, through: :appointments
end
还要确保您已向用户添加 type
列以使 single table inheritance 正常工作。
假设我只想为 rails.but ruby 中的用户制作一个 table 我想根据用户的角色再制作 2 个模型。这样我就可以在它们之间使用另一个多对多关系。
class Patient < User
has_many :appointments
has_many :physicians, through: :appointments
end
class Physician < User
has_many :appointments
has_many :physicians, through: :appointments
end
class User < ApplicationRecord
end
class Appointment < ApplicationRecord
belongs_to :physician
belongs_to :patient
end
设置约会关联时需要手动指定外键列:
class Physician < User
has_many :appointments, foreign_key: :physician_id
has_many :patients, through: :appointments
end
class Patient < User
has_many :appointments, foreign_key: :patient_id
has_many :physicians, through: :appointments
end
还要确保您已向用户添加 type
列以使 single table inheritance 正常工作。