Forum: Ruby on Rails 'If Exists' Condition?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
lists (Guest)
on 2005-11-29 02:32
(Received via mailing list)

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
orders that have at least one order line. Orders with no lines would be

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

joevandyk (Guest)
on 2005-11-29 02:40
(Received via mailing list)
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? }

I can't just do:
  self.find { |o| o.order_lines.size > 0 }
Jarkko L. (Guest)
on 2005-11-29 10:12
(Received via mailing list)
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 =

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.

This topic is locked and can not be replied to.