zzyyxxww
zzyyxxww

Reputation: 1

Writing an ActiveRecord scope with a join and "OR" condition

I have two tables: shipments and manifests.

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:

  1. if it has at least one manifest, the current time is between the start and end times, OR
  2. it has no manifests

Upvotes: 0

Views: 262

Answers (1)

Bohdan
Bohdan

Reputation: 8408

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

Upvotes: 0

Related Questions