【问题标题】:Active record query to get the count for nested associations in rails活动记录查询以获取 Rails 中嵌套关联的计数
【发布时间】:2016-07-14 19:30:43
【问题描述】:

如何编写ActiveRecord 查询以获取共享appointmentpatients 的数量(physician 可以有多个appointments

class Hospital < ActiveRecord::Base
  has_many :appointments
  has_many :patients
  has_many :physicians
end

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, through: :appointments
  belongs_to :hospital
end

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

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

我可以像Patient.first.hospital.appointments 一样得到它。但确实需要编写一个干净的 activerecord 查询,以及 hospital_id 不为空的地方

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord ruby-on-rails-3.2


    【解决方案1】:

    据我了解,您希望在某些条件下进行多个嵌套连接。这是干净的完成方式:-

    Patient.joins(:appointments => [:physician,:hospital]).where(patients:{<condition_hash_for_patient>},physicians:{<condition_hash_for_physician>},hospitals:{<condition_hash_for_hospital>})
    

    【讨论】:

    • 谢谢罗汉。 condition_hashes 有什么用?
    • 无论你想对他们施加什么条件。例如,.where(患者:{name:'vinay'},医师:{id: 1})
    • 是否可以将id not nil 放入这些条件列表中?
    • 是的,使用 .where.not(id:nil) ........你可以在这样的地方级联两个单独的 .where(患者:{name:'vinay'},医生:{id: 1}).where.not(hospitals:{id:nil}) .
    • 希望这是我的最后一个疑问。我想使用约会条件哈希。当我尝试这样做时,结果 ActiveRecord 为零。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多