Wednesday, May 30, 2007

ActiveRecord and HAVING clauses

I found myself working on a rails project a bit and for the first time had the need for a HAVING clause in a query. Hmm, that was not mentioned in the docs. Could it be missing from ActiveRecord. Yep! And not.

Found this good discussion on the subject, where Blake Watters suggests adding support for ":having" on find to the core of ActiveRecord. I agree on this being a needed feature, but there is also a mention of a work-around, that I am using now. Simply put your HAVING clause last in the ":group" key. Like this:
@upcoming_courses = Course.find(
:all,
:include => 'course_registrations',
:conditions => [ "show_online = :show AND begins_on > :now",
{:show => true, :now => DateTime.now()} ],
:order => 'begins_on asc',
:group => 'courses.id HAVING count(*) < limit =""> 3
)
And it works...

1 comment:

Anonymous said...

Thanks for the tip.