# Is there a better way to do this search?

**URL:** <https://www.ruby-forum.com/t/is-there-a-better-way-to-do-this-search/193372>\
**Category:** Rails\
**Created:** [August 16, 2010, 7:37pm UTC](https://www.ruby-forum.com/t/is-there-a-better-way-to-do-this-search/193372 "2010-08-16T19:37:28Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![bob](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/ea666f/32.png) [@bob](https://www.ruby-forum.com/u/bob)\
**Post date:** [August 16, 2010, 7:37pm UTC](https://www.ruby-forum.com/t/is-there-a-better-way-to-do-this-search/193372/1 "2010-08-16T19:37:28Z")

</div>

Here’s the situation…

:customer has\_many :billing\_windows  
:billing\_window belongs\_to :customer

A billing\_window can either be open or closed (it is considered open  
until its closed\_on attribute is set to a datetime). I’m trying to  
refactor the class method on Customer that finds all customers with at  
least 1 open billing\_window. Currently it looks like this…

def self.has\_open\_billing\_window  
set = []  
Customer.find(:all).each do |customer|  
set \<\< customer if customer.billing\_windows.find(:all, :conditions  
=\> [:open =\> true]).size \> 0  
end  
set  
end

For obvious reasons, this is horribly inefficient so I have refactored  
that code to:

def self.has\_open\_billing\_window  
Customer.find(:all, :joins =\> :billing\_windows, :conditions =\>  
“billing\_windows.closed\_on IS NULL”)  
end

This definitely seems cleaner but I don’t like the fact that the  
conditions clause is specific to the database query language. Does  
anyone know a better way to accomplish this?

Bob

---

<div class="post-metadata">

**Author:** ![bob](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/ea666f/32.png) [@bob](https://www.ruby-forum.com/u/bob)\
**Post date:** [August 16, 2010, 8:27pm UTC](https://www.ruby-forum.com/t/is-there-a-better-way-to-do-this-search/193372/2 "2010-08-16T20:27:50Z")

</div>

Bob wrote:  
[…]

> For obvious reasons, this is horribly inefficient so I have refactored  
> that code to:
> 
> def self.has\_open\_billing\_window  
> Customer.find(:all, :joins =\> :billing\_windows, :conditions =\>  
> “billing\_windows.closed\_on IS NULL”)  
> end
> 
> This definitely seems cleaner but I don’t like the fact that the  
> conditions clause is specific to the database query language.

The clause isn’t specific to the DB query language. It contains only  
standard SQL, and so should work perfectly in any SQL database.

Granted, it won’t necessary work in a non-SQL database, but those are  
typically structured very differently from SQL databases anyway.

> Does  
> anyone know a better way to accomplish this?

You don’t need one.

> Bob

## Best,

Marnen Laibow-Koser  
[http://www.marnen.org](http://www.marnen.org)  
removed\_email\_address@domain.invalid
