Rails 3 Query Interface: using associated models – Education Career Blog

I’ll use the generic blog example.

class Post < ActiveRecord::Base
  has_many :comments
class Comment < ActiveRecord::Base
  belongs_to :post

When querying Post, how do you access its associations (i.e. :comments)?

This should be the easiest thing in the world, but I haven’t found any documentation on it. Even http://edgeguides.rubyonrails.org/3_0_release_notes.html#query-interface and http://m.onkey.org/2010/1/22/active-record-query-interface were unhelpful, basically saying “Now there are methods like joins and includes to do the same thing as SQL statements.” yeah thanks.

So here are very straightforward things I want to do, which do not work, but should be obvious what I’m trying to accomplish:

Post.where(:comments.count >= 10)
Post.where(:comments.author_id == current_user.id)

How can we do these without resorting to ruby code that reeks of SQL (thus defeating the purpose of Active Record)?
Thanks 🙂


If you set up a counter_cache on Post for the comments you can see directly how many comments it has without having to query, this makes it easier and faster.

This would take care of the first and last question you posed.

You can then query them like this,

  Post.where(:comments_count >= 10)

But you are better off setting up scopes for that.

I’m not sure what you want to do with the second question, do you want to show all posts where the current user has commented on?


Post.where(:comments.count >= 10)

Post.find(:all).select{|p| p.comments.count >= 10)

Post.where(:comments.author_id == current_user.id)

Post.find(:all).select{|p| p.comments.select{|c| c.author_id == current_user.id } }


Yikes, this one beats me.

Hey also, my two posts are kinda heavy on the SQL. I know people do it more elgantly with a

Post.find(:all, :conditions => blah blah blah..

But I’m not sure how to put that. Sorry.

Leave a Comment