【问题标题】:has_many :through with multiple sourceshas_many:通过多个来源
【发布时间】:2017-03-31 01:36:57
【问题描述】:

我有一个名为AnswerConnection 的模型,它有两个来自Answer 模型的外键:answer_1answer_2

在我定义的Answer 模型中:

has_many :connections, through: :answer_connections, source: :answer_2

但是,这种关系是对称的:如果 answer_1 连接到 answer_2,则 answer_2 连接到 answer_1。这意味着当我搜索特定答案的连接时,我需要检查它是否存在于 answer_1 或 answer_2 字段中。

有可能定义一个参与这个的关系(比如如果我可以在:source 参数中定义两个值)?

【问题讨论】:

  • 听起来你想使用 has_and_belongs_to_many,或者如果你想在 AnswerConnection 模型中放置其他字段,可能会使用 has_many_through
  • 是的,我的 Answer 模型与 AnswerConnection 模型有 has many through 关系。但是,我想从我的 Answer 模型中获得它的连接,同时尊重所描述的这种对称关系。
  • 哦,抱歉,我错过了关键点,即它是一个自我参考关联。见这里:stackoverflow.com/questions/19770888/…

标签: ruby-on-rails ruby activerecord


【解决方案1】:

我认为您不能设置 2 个来源,但如果我理解正确,您可以执行以下操作:

has_many :connections_1, through: :answer_connections, source: :answer_1
has_many :connections_2, through: :answer_connections, source: :answer_2

def connections
  connections_1.merge(connections_2) # intersection
  # or connections_1.or(connections_2) for union
end

【讨论】:

  • 请注意,虽然这有效地为您提供了一个组合列表,但其他操作(例如删除连接)仍然需要额外的代码。因此,根据未来的需求,尽管这看起来比我上面链接的答案更简单,所有连接都是自动记录的,但最终很可能会变得更加复杂。
  • 这个答案在内部连接上给了我一个多重关联错误,有什么想法吗? ActiveRecord::StatementInvalid: PG::DuplicateAlias: ERROR: table name "connections" specified more than once
猜你喜欢
  • 2020-08-09
  • 2017-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多