【问题标题】:Rails Many to Many with common childrenRails 多对多与普通孩子
【发布时间】:2014-10-04 03:13:42
【问题描述】:

在我的示例应用程序中,我有

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, :through => :appointments
end

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, :through => :appointments
end

数据库模型

  • 医师:身份证、姓名
  • 约会:id、date_time、医生 ID、患者 ID
  • 患者:身份证、姓名

在一周内,我有一位医生预约看 20 位患者,其中一位患者两次。对于doc = Physician.first,如果我查看患者列表doc.patients,我会得到一份患者列表,每个预约一个,其中一名患者列出两次。我只想要一份独特患者的名单。我知道doc.patients.uniq 会给我一个独特患者的列表,但我不明白为什么这不是首先返回的内容。

如果我能解释一下为什么会这样,以及我的模型实际上是否应该采用不同的结构,我将不胜感激。

【问题讨论】:

  • 请添加您的医师模型
  • @coorasse 抱歉,我错过了将医师标记为代码。
  • 当您使用 :through 关联时,如果映射有效,则每个条目都会返回一个相关对象。您可以在此处阅读有关它的更多信息。
  • @Egalitarian 谢谢,不过我想你错过了链接。

标签: ruby-on-rails rails-activerecord


【解决方案1】:

在你的模型中你可以做

has_many :patients, -&gt; { uniq }, through: :appointments

uniq 范围需要作为第二个参数传递给 has_many。 (感谢 coorasse 更新语法。)

您会得到重复,因为 rails 会收集通过预约建立的所有患者关联,因此如果患者有多个预约,那就是多个记录,并且 rails 会收集所有记录。添加 :uniq 告诉 SQL 获取唯一记录。

【讨论】:

  • 但请注意,在 Rails 4 中,此行为已被弃用以支持范围:has_many :patients, -&gt;{ uniq }, :through =&gt; :appointments
  • 感谢 Richbits,我不知道新语法。我已批准 coorasse 的修改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-24
  • 1970-01-01
  • 2014-05-19
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 2017-04-17
相关资源
最近更新 更多