【问题标题】:sql query order problemsql查询顺序问题
【发布时间】:2011-08-07 10:00:49
【问题描述】:

所以我在activerecord中有关注模型,我会使用Discussion.user_replied_group_discussions(@user)它返回最近回复的讨论,但是我如何修改私有方法以按最近回复时间排序返回的讨论?

# 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 一起使用。但是将它放在控制器中似乎很尴尬。

有更好的解决方案吗?谢谢!

【问题讨论】:

    标签: sql ruby-on-rails sqlite activerecord


    【解决方案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
    

    【讨论】:

    • 谢谢!这完全有效!问题是,我是 Rails 新手,我不知道如何使用原始 sql 来替换 where() 方法。 :(
    • @randomor:如果您的问题没有解决,请编辑问题,使其重新出现在问题列表中。
    • 修改!感谢您的出色回答,我现在正在使用它,但想知道是否有更好的方法。
    • @yercube:谢谢,但是如果用户将两个 cmets 发布到同一个讨论中,该解决方案会导致双重讨论问题,而您的查询通过使用 MAX 函数巧妙地避免了这种问题。我想在 Rails 代码中不可能做到这一点。我将再等待 24 小时以获得更好的解决方案。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 2012-03-10
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2010-12-20
    相关资源
    最近更新 更多