我有两个资源,医生和预约。
class Doctor < ActiveRecord::Base
has_many :reservations
end
class Reservation < ActiveRecord::Base
belongs_to :doctor
end
模式:
create_table "reservations", force: true do |t|
t.integer "doctor_id"
t.date "date"
end
create_table "doctors", force: true do |t|
t.string "description"
t.datetime "created_at"
t.datetime "updated_at"
end
我想展示所有的医生在一个日期,所以所有的医生没有任何预约,在那一天。
My查询:
def index
@doctors = Doctor.all.order("created_at DESC")
@doctors = @doctors.joins(:reservations).where.not('reservations.date LIKE ?',params[:free_on]) if params[:free_on].present?
@doctors = @doctors.paginate(:page => params[:page], :per_page => 9)
end
我的问题是:结果,这个查询给了我保留。如果我在我的数据库中有一个医生和三个预约,而我选择了11月1日(在那个日期有一个预约),它会显示给我2倍于同一位医生的预约,对于不是在11月1日的2个预约。
我试过.group,但是如果有预约的话,它再一次向我展示了1名医生.
有人知道我的问题出了什么问题吗?
谢谢,
发布于 2014-10-08 15:47:36
查询的整个前提是错误的。
@doctors = @doctors.joins(:reservations).where.not('reservations.date LIKE ?',params[:free_on])
你会发现医生在"free_on“以外的日子里都有预约--不管他们是否对"free_on”有预约。这不是你想做的。你想找对"free_on“毫无保留的医生。
@doctors = @doctors.where("not exists (select * from reservations where doctor_id=doctors.id and reservations.date=?)", params[:free_on])
这应该是最优的使用索引,并运行相当快。
发布于 2014-10-08 15:16:34
你试过uniq
吗?
@doctors = @doctors.joins(:reservations).where.not('reservations.date LIKE ?',params[:free_on]).uniq
作为一个侧面,我将关注使用.date LIKE ?
来实现这样的功能。
https://stackoverflow.com/questions/26259683
复制相似问题