Writing an ActiveRecord scope with a join and "OR" condition
I have two tables: shipments and manifests.
- shipments: id, name
- manifests: id, shipment_id, start_time, end_time
A Shipment has_many Manifests, and a Manifest belongs_to one Shipment.
How do I write an ActiveRecord scope that returns me all the Shipments where:
- if it has at least 开发者_开发技巧one manifest, the current time is between the start and end times, OR
- it has no manifests
Hi I'm not sure if it can be achieved through scopes in ruby it may be sth like
shipments = Shipments.all( :include => :manifests )
empty_shipments = shipments.select { |item| item.manifests.blank? }
non_empty_shipments = shipments - empty_shipments
non_empty_shipments.delete_if {|item| (item.t_start..item.t_end).cover? Time.now}
empty_shipments & non_empty_shipments
精彩评论