我是Rails的新手,我知道這是一個簡單的問題,但它讓我發瘋。 我的應用程序是用Ruby 1.9.2和Rails 3.1構建的。 我正在寫一個應用程序來管理酒店式的房間預訂。 所以這個類代表住宿:Rails和如何使子選擇ids
class Accommodation < ActiveRecord::Base
has_many :reservations, :dependent => :destroy
end
而這一次的保留:
class Reservation < ActiveRecord::Base
belongs_to :accommodation
end
預訂確實有一個名爲accommodation_id
場,其中住宿的ID存儲
現在我必須在給定的日期範圍內檢查可用住宿,所以我寫了這種方法:
def self.check_availability(params)
# This return the unavailables accommodations
ids_to_exclude = Reservation.select(:accommodation_id).where('start_date < ? AND end_date > ?', params[:reservation_end_date], params[:reservation_start_date])
# HERE IS THE PROBLEM
accommodations = Accommodation.where("id NOT IN (?)", ids_to_exclude)
accommodations
end
第一個查詢作品,但第二個回報:
SELECT `accommodations`.* FROM `accommodation` WHERE (id NOT IN (NULL))
,我試圖輸出ids_to_exclude
,而不是NULL
我究竟做錯了什麼?
更新:
我用Arel解決了這個問題。我寫了下面
感謝您的回覆,但是我發現Arel避免了'每個do'塊的解決方案 –