ActiveRecord Query Interface - Association with conditions
I have a Post model that has_many :comments. The question is: how can I build a query using ActiveRecord Query Interface that retrieves all posts and the last comment of each posts?
All I have right now is the following, but it doesn't filter the comments and I have no idea of what to do next:
Well, the simplest thing comes to mind, which may not be the best is creating a scope.
class Post < ActiveRecord::Base # has_many or maybe a has_one ? I don't have time to fire up console again to check, sorry! has_many :last_comment, :class_name => 'Comment', :limit => 1, :order => 'comments.created_at DESC' end
And then use
Be sure you have indexes in your SQL.