Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql Rails活动记录,从has_many中获取相关记录:通过记录上的where子句的关系_Mysql_Ruby On Rails_Activerecord - Fatal编程技术网

Mysql Rails活动记录,从has_many中获取相关记录:通过记录上的where子句的关系

Mysql Rails活动记录,从has_many中获取相关记录:通过记录上的where子句的关系,mysql,ruby-on-rails,activerecord,Mysql,Ruby On Rails,Activerecord,我与建立了关系,通过建立了许多关系 class Physician < ActiveRecord::Base has_many :appointments has_many :patients, through: :appointments end class Appointment < ActiveRecord::Base belongs_to :physician belongs_to :patient # physician_id, patient_id

我与
建立了关系,通过
建立了许多关系

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

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

  # physician_id, patient_id
end


class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, through: :appointments
end
class医生
在预约角色等于PI或G2的情况下,如何为给定的医生获取所有患者

我尝试了
内科医生.查找(50).预约.其中('role=?或role=?','PI','G2')。患者

编辑:


我从上面得到了未定义的方法。难道我不应该得到通关的相关记录吗?在
medicine.find(50).appointment.where('role=?或role=?','PI','G2')
中,应该有一个
appointments
方法,但没有。

既然您想要回患者对象,就从该模型开始。您想在预约和医生上添加WHERE条款,所以请加入这些协会。使用
where
的散列形式引用联接的表

Patient.joins(:physician).
  joins(:appointments).
  where(appointments: {role: ["PI", "G2"]}).
  where(physicians: {id: physician_id}).uniq
更新

考虑向模型中添加可重用的范围:

class Patient < ActiveRecord::Base
  scope :for_physician, ->(physician_id) do
    joins(:physicians).
    where(physicians: {id: physician_id}
  end

  scope :for_roles, ->(roles) do
    joins(:appointments).
    merge(Appointment.for_roles(roles))
  end
end

class Appointment < ActiveRecord::Base
  scope :for_roles, ->(roles) do
    where(role: roles)
  end
end
Patient.for_physician(50).for_roles(["PI", "G2"]).uniq