具有多种条件的范围

时间:2012-02-17 20:07:27

标签: ruby-on-rails ruby-on-rails-3

我有一张医生表,医生有doctor_id,hospital_id,dept_id

如何编写范围,我可以说:选择与当前doctor_id具有相同hospital_id相同dept_id的所有doctore,但不包括当前的doctor_id

1 个答案:

答案 0 :(得分:2)

这是作为范围:

class Doctor < ActiveRecord::Base
  def self.other_docs_in_dept(doc)
    Doctor.where(dept_id: doc.dept_id)
          .where(hospital_id: doc.hospital_id)
          .where("id != #{doc.id}")
  end
end

...但作为一种实例方法,这可能对你更有效:

class Doctor < ActiveRecord::Base
  def other_docs_in_dept
    Doctor.where(dept_id: dept_id)
          .where(hospital_id: hospital_id)
          .where("id != #{id}")
  end
end