2010-12-22 133 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)