简体   繁体   English

如何通过 has_many 关联创建一个 has_one?

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

Context: I have 2 models ClinicalSystem and TemplateMessage上下文:我有 2 个模型ClinicalSystemTemplateMessage

My goal: is to have ClinicalSystem with many TemplateMessage but also have multiple has_one realtion with TemplateMessage with different namings.我的目标:是拥有具有许多TemplateMessageClinicalSystem ,但也拥有多个具有不同命名的TemplateMessage的 has_one 实体。 eg:例如:

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.我试过has_many: through但它失败了。

You can define the main has_many association and the has_one associations separately like below:您可以分别定义主has_many关联和has_one关联,如下所示:

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

You can achieve that using foreign_key and class_name您可以使用foreign_keyclass_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您还需要添加迁移以在临床系统表中添加foreign_keys reschedule_template_message_idcancellation_template_message_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM