命名范围和关联

时间:2010-12-22 22:43:57

标签: ruby-on-rails-3

我有货运,旅行和预订。

cargo_request has_many行程(并非所有行程都属于freight_request)

旅行有很多预订(所有预订都属于旅行)

我正在尝试为freight_requests编写一个范围,以获取未预订的所有cargo_requests。这包括没有旅行的货运申请,以及确实有旅行但没有预订旅行的货运申请。

目前我有

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代码没有返回没有跳闸的cargo_requests(它什么都不返回)。

任何人对我如何做到这一点都有任何想法? Thx提前

1 个答案:

答案 0 :(得分:0)

我猜你忘记了Trip模型中的include:no_trip scope。

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)

相关问题