I have two models
class Checkout
has_one :order
end
class Order
belongs_to :checkout
end
I need to find all checkouts that has no order yet. How can I do it with rails?
I have two models
class Checkout
has_one :order
end
class Order
belongs_to :checkout
end
I need to find all checkouts that has no order yet. How can I do it with rails?
Use left outer join
that would give you all checkouts joined with orders. Then select rows without orders (order.id == nil
)
Chceckout.left_outer_join(:orders).where('orders.id' => nil)
The trick here is that includes() expects the name of the association but the where expects the name of the table. For a has_one the association will generally be expressed in the singular, so that changes, but the where() part stays as it is.So statement would be:
Checkout.includes(:order).where( :orders=> { :orders_id=> nil } )