Skip to content

Instantly share code, notes, and snippets.

@pedrodelgallego
Created November 29, 2009 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedrodelgallego/244955 to your computer and use it in GitHub Desktop.
Save pedrodelgallego/244955 to your computer and use it in GitHub Desktop.
==== Error
ActiveRecord::StatementInvalid (PGError: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 1: ...comments ON comments.post_id = posts.id ORDER BY comments.c...
^
: SELECT distinct posts.* FROM "posts" INNER JOIN comments ON comments.post_id = posts.id ORDER BY comments.created_at DESC LIMIT 5):
app/models/comment_activity.rb:18:in `find_recent'
app/controllers/admin/dashboard_controller.rb:4:in `show'
===== Controller
class Admin::DashboardController < Admin::BaseController
def show
@posts = Post.find_recent(:limit => 8)
@comment_activity = CommentActivity.find_recent
@stats = Stats.new
end
end
===== Method
class CommentActivity
attr_accessor :post
def initialize(post)
self.post = post
end
def comments
@comments ||= post.approved_comments.find_recent(:limit => 5)
end
def most_recent_comment
comments.first
end
class << self
def find_recent
Post.find(:all,
:select => 'distinct posts.*',
:joins => 'INNER JOIN comments ON comments.post_id = posts.id',
:order => 'comments.created_at DESC',
:limit => 5
).collect {|post|
CommentActivity.new(post)
}.sort_by {|activity|
activity.most_recent_comment.created_at
}.reverse
end
end
end
class << self
def find_recent
Post.find(:all,
:select => 'distinct posts.*',
:include => [:comments],
:order => 'comments.created_at DESC',
:limit => 5
).collect {|post|
CommentActivity.new(post)
}.sort_by {|activity|
activity.most_recent_comment.created_at
}.reverse
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment