Rails查询多对多

时间:2015-10-28 12:47:47

标签: ruby-on-rails

快速提问。鉴于以下example多对多关系,我如何查询Physician表中的约会?

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

在Physician模型上,我有以下内容:

scope :for, -> (name) { find_by_name(name: name) }
# I need a hand here, the join I assumed would work didn't seem to filter properly.
# scope :appointments_today, -> { joins(:appointment).where("appointments.appointment_date = ?", Date.today) }
scope :appointments_today, -> { ??? }

我想在控制器上链接查询:

data = Physician.for("test").appointments_today

3 个答案:

答案 0 :(得分:0)

如果您尝试获取约会列表,逻辑应该进入Appointment模型:

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

  scope :for_today, -> { where('appointments.appointment_date >= ? AND appointments.appointment_date < ?', Time.zone.now.beginning_of_day, Time.zone.now.end_of_day) }

  scope :for_physician, -> (name) { joins(:physician).where(physicians: {name: name}) }
end

您可以通过以下方式找到约会:

data = Appointment.for_today.for_physician("test")

答案 1 :(得分:0)

尝试这样做

scope :for, -> (name) { where(name: name) }

接下来,您必须在appointments

中添加复数
scope :appointments_today, -> { joins(:appointments).where("appointments.appointment_date = ?", Date.today) }

我希望这对你有所帮助。

答案 2 :(得分:0)

您是否需要今天安排预约的Physician条记录列表,或者您是否需要针对特定​​医生并且计划今天安排的Appointment条记录列表?

今天有预约的医生:

Physician.
  joins(:appointments).
  where(
    name: "test",
    appointments: {
      appointment_date: (Date.today.beginning_of_day..Date.today.end_of_day)
    }
  )

今天的医生预约:

Appointment.
  joins(:physician).
  where(
    appointment_date: (Date.today.beginning_of_day..Date.today.end_of_day),
    physicians: { name: "test" }
  )

作为范围,你可以做今天预约的医生:

class Physician < ActiveRecord::Base
  scope :named, -> (name) { where(name: name) }
  scope :with_appointments_on, -> (date) { joins(:appointments).where(appointments: { appointment_date: (date.beginning_of_day..date.end_of_day) })}
end

Physician.named("test").with_appointments_on(Date.today)

或今天的医生预约:

class Appointment < ActiveRecord::Base
  scope :on_date, -> (date) { where(appointment_date: (date.beginning_of_day..date.end_of_day)) }
end

Physician.find_by_name("test").appointments.on_date(Date.today)