【问题标题】:Rails filtering conditions on HABTM join tableHABTM 连接表上的 Rails 过滤条件
【发布时间】:2014-04-16 01:13:34
【问题描述】:
 class Physician < ActiveRecord::Base
   has_many :appointments
   has_many :patients, through: :appointments
 end

 class Appointment < ActiveRecord::Base
   belongs_to :physician
   belongs_to :patient
   scope :physicals, -> { where appointment_type: 'physical' }
 end

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

如何在一个查询中为医生访问带有体检的患者列表?反过来(有不同类型的不同约会的患者)?然后我可以用physician.patients_with_physicals = [patient] 之类的东西来设置它吗?

【问题讨论】:

  • 首先,不是HABTM,而是has_many =&gt;through

标签: sql ruby-on-rails activerecord scope has-and-belongs-to-many


【解决方案1】:

以下将允许您在单个查询中获取任何类型的患者:

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, through: :appointments

  def patients_with_appointment_of_type type
    self.patients.joins(:appointments)
      .where(:appointments => {:type => type})
  end
end

您希望在哪里使用physician.patients_with_physicals = [patient] 您打算如何填写我认为需要的其他约会数据(时间等)?

值得注意的是,Rails 使用type 作为列来表示使用单表继承 (STI) 的模型,这可能会给您带来问题,因此我建议您使用不同的列名。

【讨论】:

  • 我会将字段更改为除类型以外的其他内容
  • 您对如何设置剩余约会数据(时间、日期等)的问题有答案吗?通过某种方法(如问题中所示)添加患者时,您可以通过多种方式设置约会类型,但如果要考虑其他数据,可能会有更好的方法。
【解决方案2】:

对于医生,我如何访问患者列表,并在 单个查询?

使用ActiveRecord Association Extensions:

#app/models/physician.rb
Class Physician < ActiveRecord::Base
    has_many :appointments
    has_many :patients, through: :appointments do
        def with(type)
           where(appointment_type: type)
        end
    end
end

#-> @doctor.patients.with("physicals")
#-> Patient #1 etc

你能解释一下你的意思吗:

有不同类型的不同预约的患者)?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-10
    • 2012-09-23
    • 2011-03-21
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多