【问题标题】:Rails 5: "belongs_to through" kind of associationRails 5:“belongs_to through”类关联
【发布时间】:2017-05-16 00:42:26
【问题描述】:

祝大家新年快乐!

我有经典has_many through association

class Physician < ApplicationRecord
  has_many :appointments
  has_many :patients, through: :appointments
end

class Appointment < ApplicationRecord
  belongs_to :physician
  belongs_to :patient
end

class Patient < ApplicationRecord
  has_many :appointments
  has_many :physicians, through: :appointments
end

但是现在我需要将has_many 关联从class Appointment 添加到一些class Example,该关联与另一个模型在belongs_to 关联中,并且将在与@ 的belongs_to 关联中987654329@.

如果可能,如何设置这种关联?谢谢。

更新

我不明白,为什么这个问题被否决了。 这是我在class Example 中需要的:

class Example < ApplicationRecord
  belongs_to :appointment
  belongs_to :model_bbb
end

更新 2

好的,我发现我可以使用this answer 的解决方案。基本上我可以放弃“约会”模型并拥有像这样的class Example

class Example < ApplicationRecord
  belongs_to :physician
  belongs_to :patient
  belongs_to :model_bbb
end

然后在医师和患者中,我可以建立has_many :examples 和另一个through 关系。我确实想做一些奇怪的belongs_to through 事情,因为我可以拥有相对较小的class Appointment 表,但class Example 表预计会很大。所以我最初的想法是不要创建会重复很多次的额外列。

【问题讨论】:

  • 问题无法理解。那么,你上次的 sn-p 有什么问题?顺便说一句,请编辑标签以改进分类 - 因为这是一个 ruby​​-on-rails-5 线程。

标签: ruby-on-rails ruby activerecord ruby-on-rails-5


【解决方案1】:

您可以将 has_many 或 has_many 添加到您的 Appointment 模型类中。

请记住,belongs_to 关联始终在具有外键的表上。因此,如果您的建模正确,您应该在示例表中有一个约会 ID,例如。

使用关联表与另一个关联表没有问题。实际上,使用中间表的想法是能够在其上存储其他信息(否则您将使用 HABTM)。

【讨论】:

  • 谢谢,请检查我上面的更新 2。目前这对我来说似乎是最有效的解决方案。如果您有任何其他想法,请发表评论。
猜你喜欢
  • 2011-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多