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.
CodePudding user response:
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
CodePudding user response:
You can achieve that using foreign_key
and class_name
class ClinicalSystem
has_many :tempalte_messages
belongs_to :reschedule_template_message, foreign_key: 'reschedule_template_message_id', class_name: 'TemplateMessage'
belongs_to :cancellation_template_message, foreign_key: 'cancellation_template_message_id', class_name: 'TemplateMessage'
end
You will also need to add migration to add foreign_keys reschedule_template_message_id
and cancellation_template_message_id
in the clinical_systems table