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:

Post.includes(:comments)

Answers


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

Post.includes(:last_comment)

Be sure you have indexes in your SQL.


Need Your Help

Unresolved externals and some warnings while building the qt solution

c++ visual-studio qt

I have Qt libraries 4.8.1 for Windows (VS 2010 ultimate) with Qt Visual Studio Add-in. This is my very simple app :

HTTP Status 500 - can't create directory /var/lib/tomcat7/webapps/ROOT/WEB-INF/lucee

ubuntu tomcat nginx coldfusion lucee

I'm new to Linux (Ubuntu 16.04)and working on trying to setup Lucee 5, Ubuntu, Tomcat, and nginx. I feel like I'm close to it working, but getting this error 500 when going to the page (sometestfi...