2014-10-08 19 views
1

我有2資源,醫生和保留。Rails 4連接查詢顯示錯誤的資源

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 

我要顯示所有的日期可用的醫生,讓所有不必須在那一天任何保留醫生。

我的查詢:

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 

我的問題是: 該查詢給我保留意見的結果。 如果我在我的數據庫中有1名醫生和3次預約,並且我選擇了11月1日(當天有1次預約),它顯示我是同一位醫生的2次,因爲2次預約不在11月1日。

我試過。集團,但它再次表明我只有1名醫生,如果有預約...

有人有什麼毛病我查詢的想法?

謝謝

+0

嘗試包括而不是加入?通常你應該更喜歡包括加入... – user3334690 2014-10-08 14:42:59

+0

Thx爲你的幫助,但同樣的問題。 – Devlesch 2014-10-08 14:50:35

回答

0

您的查詢的整個前提是錯誤的。

@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]) 

這應該是優化使用指標和運行速度非常快。

+0

就是這樣。非常感謝 – Devlesch 2014-10-08 15:53:40

0

您試過uniq

@doctors = @doctors.joins(:reservations).where.not('reservations.date LIKE ?',params[:free_on]).uniq 

一點題外話,我會用.date LIKE ?這樣的功能有關。

+0

感謝您的幫助。 使用.uniq它給我一個結果,而不是3,但問題依然如故。我認爲我的查詢不正確。 對於你的旁註,你會用什麼? (我正在學習) – Devlesch 2014-10-08 15:27:16