Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all objects with no associated has_many objects

In my online store, an order is ready to ship if it in the "authorized" state and doesn't already have any associated shipments. Right now I'm doing this:

class Order < ActiveRecord::Base
    has_many :shipments, :dependent => :destroy

    def self.ready_to_ship
        unshipped_orders = Array.new
        Order.all(:conditions => 'state = "authorized"', :include => :shipments).each do |o|
            unshipped_orders << o if o.shipments.empty?
        end
        unshipped_orders
    end
end

Is there a better way?

like image 684
Tom Lehman Avatar asked Apr 25 '09 02:04

Tom Lehman


1 Answers

In Rails 3 using AREL

Order.includes('shipments').where(['orders.state = ?', 'authorized']).where('shipments.id IS NULL')
like image 149
s01ipsist Avatar answered Oct 10 '22 18:10

s01ipsist