开发者

sql query order problem

开发者 https://www.devze.com 2023-02-27 03:09 出处:网络
So I\'ve got the follow model in activerecord, I will use Discussion.user_replied_group_discussions(@user)it returns the recent replied discussions alright, but how do I modify the private method to o

So I've got the follow model in activerecord, I will use Discussion.user_replied_group_discussions(@user)it returns the recent replied discussions alright, but how do I modify the private method to order the returned discussions by latest reply time?

# 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 =开发者_Python百科> 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

UPDATE: The sql query provided by @ypercube helped, I'm now using it with find_by_sql. But it seems awkward putting that in the controller.

Is there a better solution? Thanks!


This will order according to latest discussions.updated_at time:

where("discussable_type = 'Group' AND id IN (#{discussion_ids}) 
order by updated_at DESC ",

If you want to order by comment.created_at, use this query:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消