2011-04-17 126 views
1

所以我在activerecord中有了跟隨模型,我將使用Discussion.user_replied_group_discussions(@user)它返回最近回覆的討論好吧,但是如何修改私有方法以按最新回覆時間排序返回的討論?SQL查詢命令問題

# 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 

UPDATE: 由@ypercube提供的SQL查詢的幫助下,我現在用它的find_by_sql。但把它放在控制器中似乎很尷尬。

有沒有更好的解決方案?謝謝!

回答

1

這將根據最新discussions.updated_at時間順序:

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

如果您想通過comment.created_at訂購,使用此查詢:

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

謝謝!完全有效!問題是,我是一個rails新手,我不知道如何使用原始的sql來替換where()方法。 :( – randomor 2011-04-17 18:57:49

+0

@randomor:如果你的問題沒有解決,編輯問題,所以它在問題列表中重新出現。 – 2011-04-18 05:30:09

+0

已修改!謝謝你的好回答,但我現在正在使用它,但想知道是否有更好的方法。 – randomor 2011-04-18 06:02:47