[SOLVED] How to make a has_one through has_many association?

Issue

This Content is from Stack Overflow. Question asked by Merey Nurlan

Context:
I have 2 models ClinicalSystem and TemplateMessage

My goal: is to have ClinicalSystem with many TemplateMessage but also have multiple has_one realtion with TemplateMessage with different namings. e.g:

clinical_system.tempalte_messages, clinical_system.reschedule_template_message, clinical_system.cancellation_template_message.

How do I structure my associations to achieve that ? I have tried has_many: through but it failed.



Solution

You can define the main has_many association and the has_one associations separately like below:

class ClinicalSystem
  has_many :tempalte_messages
  has_one :reschedule_template_message, -> { CONDITION_FOR_RESCHEDULE }, class_name: TemplateMessage.name
  has_one :cancellation_template_message, -> { CONDITION_FOR_CANCELLATION }, class_name: TemplateMessage.name
end


This Question was asked in StackOverflow by Merey Nurlan and Answered by Sachin Singh It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?