views:

291

answers:

1

Hi there,

First SO question after using this place for reference on a lot of other things.. I'm nervous.

DataMapper.. Using Blog model for example (posts, comments etc - http://datamapper.org/docs/associations.html) I'm trying to workout how to get the blog posts that don't have any comments..

So something like Post.all(:comments => { :comment => nil })

Lot having much luck :(

I read on here that for complex reporting queries it's best to drop down to SQL, but surely there's a way of doing this isn't there SO?

Thanks in advance.

+2  A: 

If you don't have a counter cache in your Post model (called eg "comments_count"), this is going to be slow. But here it is anyway:

Post.find(:all, :include => :comments).select { |post| post.comments.empty? }

I would suggest going with the counter cache solution (but that involves some schema refactoring and updating the counters during migration one time):

Post.all(:conditions => { :comments_count => 0 })

The latter being much more efficient, especially in Rails 3 (cause of lazy querying).

hurikhan77