sql查询顺序问题

| 因此,我在activerecord中有一个跟随模型,我将使用ѭ0来返回最近回复的讨论,但是如何修改私有方法以按最近的回复时间对返回的讨论进行排序?
# Table name: discussions
#
#  id               :integer         not null, primary key
#  title            :string(255)     not null
#  content          :text(255)       not null
#  created_at       :datetime
#  updated_at       :datetime
#  user_id          :integer
#  discussable_id   :integer
#  discussable_type :string(255)
class Discussion < ActiveRecord::Base
  has_many    :comments, :as => :commentable, :dependent => :destroy
  #
  #this is the scope that I am having trouble with:
  #
  scope :user_replied_group_discussions, lambda {|user| replied_by(user) }

  private
    def self.replied_by(user)
      discussion_ids = %(SELECT commentable_id FROM comments 
                     WHERE commentable_type = \'Discussion\' AND user_id = :user_id)
      where(\"discussable_type = \'Group\' AND id IN (#{discussion_ids}) \", 
           { :user_id => user })
    end
end

# Table name: comments
#
#  id               :integer         not null, primary key
#  content          :text
#  created_at       :datetime
#  updated_at       :datetime
#  commentable_id   :integer
#  commentable_type :string(255)
#  user_id          :integer
#

class Comment < ActiveRecord::Base

  belongs_to :commentable, :polymorphic => true
  belongs_to :user

end
更新: @ypercube提供的sql查询有帮助,我现在将它与find_by_sql一起使用。但是将其放入控制器似乎很尴尬。 有更好的解决方案吗?谢谢!     
已邀请:
这将根据最近的
discussions.updated_at
时间排序:
where(\"discussable_type = \'Group\' AND id IN (#{discussion_ids}) 
order by updated_at DESC \",
如果要按4英镑订购,请使用以下查询:
SELECT d.*
     , MAX(c.created_at) AS lastCommentTime
FROM discussions d
  JOIN comments c
    ON d.id = c.commentable_id
WHERE c.commentable_type = \'Discussion\'
  AND c.user_id = userIDtoCheck
GROUP BY d.id
ORDER BY lastCommentTime DESC        <--- latest first
    

要回复问题请先登录注册