首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Rails 4联接查询显示错误的资源

Rails 4联接查询显示错误的资源
EN

Stack Overflow用户
提问于 2014-10-08 14:38:58
回答 2查看 41关注 0票数 1

我有两个资源,医生和预约。

代码语言:javascript
运行
复制
class Doctor < ActiveRecord::Base
    has_many :reservations
end

class Reservation < ActiveRecord::Base
    belongs_to :doctor
end

模式:

代码语言:javascript
运行
复制
  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查询:

代码语言:javascript
运行
复制
  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名医生.

有人知道我的问题出了什么问题吗?

谢谢,

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-10-08 15:47:36

查询的整个前提是错误的。

代码语言:javascript
运行
复制
@doctors = @doctors.joins(:reservations).where.not('reservations.date LIKE ?',params[:free_on])

你会发现医生在"free_on“以外的日子里都有预约--不管他们是否对"free_on”有预约。这不是你想做的。你想找对"free_on“毫无保留的医生。

代码语言:javascript
运行
复制
@doctors = @doctors.where("not exists (select * from reservations where doctor_id=doctors.id and reservations.date=?)", params[:free_on])

这应该是最优的使用索引,并运行相当快。

票数 0
EN

Stack Overflow用户

发布于 2014-10-08 15:16:34

你试过uniq吗?

代码语言:javascript
运行
复制
@doctors = @doctors.joins(:reservations).where.not('reservations.date LIKE ?',params[:free_on]).uniq

作为一个侧面,我将关注使用.date LIKE ?来实现这样的功能。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26259683

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档