协会不工作

我有三个型号:

部门

class Department  :destroy has_many :waitingrooms, :dependent => :destroy end 

等候室与字段patient_id:integerdepartment_id:integer

 class Waitingroom < ActiveRecord::Base belongs_to :patient end 

department_id:integer 患者 department_id:integer

 class Patient < ActiveRecord::Base belongs_to :department has_many :waitingrooms end 

病人在候诊室后,我救了一间候诊室! 所以现在我试图找回那些在部门候诊室里的病人:

  def index @waited = @current_department.waitingrooms.patients end 

不知何故,它没有工作,它返回此错误:

 undefined method `patients' for # 

但这很奏效:我错了什么? 谢谢!

  def index @waited = @current_department.waitingrooms end 

您无法在集合上调用关联。 您需要在特定记录上调用它。 如果你想让一群等候室的所有病人,你需要这样做:

 def index rooms = @current_department.waitingrooms @waited = rooms.map { |r| r.patients } end 

如果你想要一个平面数组,你可以(作为一个天真的第一遍)使用rooms.map { |r| r.patients }.flatten.uniq rooms.map { |r| r.patients }.flatten.uniq 。 更好的尝试只需构建患者ID列表并获取一次患者:

 @waited = Patient.where(id: rooms.pluck(:patient_id).uniq)