Association not working

2019-09-02 01:37发布

问题:

I have three models:

Department

class Department < ActiveRecord::Base
    has_many :patients, :dependent => :destroy
    has_many :waitingrooms, :dependent => :destroy
end

Waitingroom with fields patient_id:integer and department_id:integer

class Waitingroom < ActiveRecord::Base
    belongs_to :patient
end

Patient with department_id:integer

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

I save a waitingroom after a patient was in the waitingroom! So now i tried to retrieve the patients who where in the the waitingroom of the department:

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

Somehow it didnt worked it returned this error:

undefined method `patients' for #<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Waitingroom:0x374c658>

But this worked: What did i wrong? Thanks!

  def index
    @waited = @current_department.waitingrooms  
  end

回答1:

You can't invoke an association on a collection. You need to invoke it on a specific record. If you want to get all the patients for a set of waiting rooms, you need to do this:

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

If you want a flat array, you could (as a naive first pass) use rooms.map { |r| r.patients }.flatten.uniq. A better attempt would just build a list of patient ids and fetch patients once:

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