On Mar 5, 2011, at 4:04 PM, Mark Sobkowicz wrote:

> I have a query I'd like to put in a named_scope.   I have a model Item and a 
> model Rental.   Item has_many rentals, Rental has_one item.   Rental has a 
> boolean field "active".   I'd like to make a named scope that finds all the 
> items with no active rental.  

Can you be more specific about the associations? I suspect what you've got is 
actually Rental belongs_to Item (so the 'rentals' table has a field 
'item_id')...

Assuming that's the case, the *query* to find the items would look like:

Item.find(:all, :joins => 'OUTER JOIN rentals ON rentals.item_id = items.id AND 
rentals.active = 1', :conditions => 'rentals.id IS NULL')

so the corresponding scope (on the Item model) would be:

named_scope :without_active_rentals, :joins => 'OUTER JOIN rentals ON 
rentals.item_id = items.id AND rentals.active = 1', :conditions => 'rentals.id 
IS NULL'

(this is Rails 2 syntax, conversion to the ARel-style should be straightforward)

---

Note: I was really hoping this would work (in the Item model):

has_many :active_rentals, :class_name => 'Rental', :conditions => { :active => 
true }

then getting the Item.without_active_rentals for free from the automatic scopes 
system. (You get without_rentals from that, but it's not quite what's needed).

But it appears that exists_sql_condition doesn't take association conditions 
into account. Bummer. :)

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups "Hobo 
Users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/hobousers?hl=en.

Reply via email to