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
237 views
in Technique[技术] by (71.8m points)

ruby on rails - How to retrieve associated records through more than one other table?

Here's a simple setup where the user will always be a patient, and the user may or may not also be a physician:

# user.rb
  has_one :physician
  has_one :patient
# physician.rb
  belongs_to :user
  validates_uniqueness_of :user_id
  has_many :appointments
  has_many :patients, :through => :appointments
# patient.rb
  belongs_to :user
  validates_uniqueness_of :user_id 
  has_many :appointments
  has_many :physicians, :through => :appointments

It all connects to appointments and then to conversations, like so:

# appointment.rb
  belongs_to :physician
  belongs_to :patient
  has_one :conversation
  has_many :messages, through: :conversation
# conversation.rb
  belongs_to :appointment
  belongs_to :sender, foreign_key: :sender_id, class_name: "User"
  belongs_to :recipient, foreign_key: :recipient_id, class_name: "User"
  has_many :messages

Sometimes I really want to be able to do this:

current_user.conversations

but that doesn't work, and instead I would have to do something like this:

current_user.physician.appointment.includes(:conversation)
# somehow combine results with this
current_user.patient.appointment.includes(:conversation)

Question

What do I need to do (and where) so that I can call current_user.conversations and it will retrieve all the conversations (i.e. those as a patient, and those as a physician (noting the user may or may not be a physician).

Note: open to suggestion if what I'm suggesting isn't good practice.

question from:https://stackoverflow.com/questions/65922139/how-to-retrieve-associated-records-through-more-than-one-other-table

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

1 Answer

0 votes
by (71.8m points)

Based on your current design, in the User model, you can simply add a method for conversations:

def conversations
  Conversation.where(sender: self).or(Conversation.where(recipient: self))
end

I am not sure why a conversation would have a sender and recipient as a user can be both a sender (of a message) and recipient (of a message) in a conversation. I would drop the sender_id and recipient_id from the conversations table and just match the conversations based on appointments.

def conversations
  Conversation
   .joins(appointment: [:physician, :patient])
   .where('physicians.user_id = :user_id or patients.user_id = :user_id', user_id: id)
end

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

...