'If Exists' Condition?


#1

Hello,

I have two models:

Order (has_many :order_lines)
OrderLine (belongs_to :order)

I would like to come up with a find for the Order model that only gives
me
orders that have at least one order line. Orders with no lines would be
excluded.

Can someone give me a tip as to the best way to phrase that to
ActiveRecord?

Thanks,
H


#2

On 11/28/05, Hunter H. removed_email_address@domain.invalid wrote:

Can someone give me a tip as to the best way to phrase that to ActiveRecord?

Inefficient one:

class Order < AR
def real_orders
orders = []
self.find(:all).each { |o| orders << o unless o.order_lines.empty? }
orders
end
end

I can’t just do:
self.find { |o| o.order_lines.size > 0 }
right?


#3

On 29.11.2005, at 2.31, Hunter H. wrote:

would be
excluded.

Just use the normal find method with :joins => “inner join
order_lines”. Inner join only gives you the rows that have a(t least
one) matching row in the joined table.

All in all, I’d recommend doing the screening in the db end.

def self.find_all_with_lines
find :all, :joins => “inner join order_lines on orders.id =
order_lines.order_id”
end

Note that the orders will be returned read_only by default. However,
that is less of a problem that you might think, since you rarely edit
objects in the same action where you fetch them. You can also
override this behaviour by passing the find method :readonly => false.

//jarkko