Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
870 views
in Technique[技术] by (71.8m points)

orm - 2 different model based on one attribute of a table in rails

Suppose I want to make only one table for users in ruby on rails.but I want to make 2 more model based on the role of the user. So that I can use another many to many relation between them.

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
question from:https://stackoverflow.com/questions/65647548/2-different-model-based-on-one-attribute-of-a-table-in-rails

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When setting up the appointments association you need to manually specify the foreign key column:

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

Also make sure you have added a type column to users to get single table inheritance working.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...