2010-12-22 185 views
1

我有freight_requests,旅行和預訂。命名範圍和協會

一個freight_request的has_many旅行(不是所有的車次屬於freight_request)

之旅的has_many預訂(所有預訂屬於跳閘)

我想寫一個作用域freight_requests是得到所有沒有預訂的freight_requests。這包括沒有行程的freight_request,以及確實有行程但沒有預訂行程的freight_request。

目前,我有

trip.rb

has_many :bookings 
scope :not_booked, where("trips.id NOT IN (SELECT trip_id FROM bookings)") 

booking.rb

belongs_to :trip 

freight_request.rb

has_many :trips 
scope :not_booked, joins(:trips) & Trip.not_booked 
scope :no_trip, where("freight_requests.id NOT IN (SELECT freight_request_id FROM trips)") 

問題是no_trip代碼沒有按沒有退貨freight_requests沒有旅行(它什麼都沒有返回)。

任何人有任何想法,我怎麼能做到這一點? Thx提前

回答

0

我想你忘了包含在trip模型中:no_trip範圍。

scope :no_trip, includes(:trips).where("freight_requests.id NOT IN (SELECT freight_requests_id FROM trips)")

我也想指出,這個查詢遍歷所有行程記錄,如果你有大量的數據,這可能是昂貴的。在FreightRequest模型中的計數器緩存可能是更快的方式,在這種情況下,您的no_trip範圍將爲:

scope :no_trip, where(:trips_counter => 0)