11

我用新scope方法遇到了一点问题(Arel 0.4.0,Rails 3.0.0.rc)

基本上我有:

一个topics模型, whichhas_many :comments和一个comments模型(带有一topic_id列) which belongs_to :topics

我正在尝试获取“热门话题”的集合,即最近评论的话题。当前代码如下:

# models/comment.rb
scope :recent, order("comments.created_at DESC")

# models/topic.rb
scope :hot, joins(:comments) & Comment.recent & limit(5)

如果我执行Topic.hot.to_sql,将触发以下查询:

SELECT "topics".* FROM "topics" INNER JOIN "comments"
ON "comments"."topic_id" = "topics"."id"
ORDER BY comments.created_at DESC LIMIT 5

这很好用,但它可能会返回重复的主题 - 如果主题 #3 最近被多次评论,它将被多次返回。

我的问题

我将如何返回一组不同的主题,记住我仍然需要访问该comments.created_at字段,以显示上一篇文章是多久以前的?我会想象一些类似于distinctor的东西group_by,但我不太确定如何最好地去做。

任何建议/建议都非常感谢 - 我已经添加了 100 个代表的赏金,希望很快能找到一个优雅的解决方案。

4

4 回答 4

5

解决方案 1

这不使用 Arel,而是使用 Rails 2.x 语法:

Topic.all(:select => "topics.*, C.id AS last_comment_id, 
                       C.created_at AS last_comment_at",
          :joins => "JOINS (
             SELECT DISTINCT A.id, A.topic_id, B.created_at
             FROM   messages A,
             (
               SELECT   topic_id, max(created_at) AS created_at
               FROM     comments
               GROUP BY topic_id
               ORDER BY created_at
               LIMIT 5
             ) B
             WHERE  A.user_id    = B.user_id AND 
                    A.created_at = B.created_at
           ) AS C ON topics.id = C.topic_id
          "
).each do |topic|
  p "topic id: #{topic.id}"
  p "last comment id: #{topic.last_comment_id}"
  p "last comment at: #{topic.last_comment_at}"
end

确保索引表中的created_atandtopic_idcomments

解决方案 2

在模型中添加一last_comment_id列。创建评论后Topic更新。last_comment_id这种方法比使用复杂的 SQL 来确定最后一条评论要快得多。

例如:

class Topic < ActiveRecord::Base
  has_many :comments
  belongs_to :last_comment, :class_name => "Comment"
  scope :hot, joins(:last_comment).order("comments.created_at DESC").limit(5)
end

class  Comment
  belongs_to :topic

  after_create :update_topic

  def update_topic
    topic.last_comment = self
    topic.save
    # OR better still
    # topic.update_attribute(:last_comment_id, id)
  end
end

这比运行复杂的 SQL 查询来确定热门话题要高效得多。

于 2010-08-27T05:14:10.020 回答
3

在大多数 SQL 实现中,这并不是那么优雅。一种方法是首先获取按 topic_id 分组的五个最近评论的列表。然后通过使用 IN 子句进行子选择来获取 comments.created_at。

我对 Arel 很陌生,但这样的事情可能会奏效

recent_unique_comments = Comment.group(c[:topic_id]) \
                                .order('comments.created_at DESC') \
                                .limit(5) \
                                .project(comments[:topic_id]
recent_topics = Topic.where(t[:topic_id].in(recent_unique_comments))

# Another experiment (there has to be another way...)

recent_comments = Comment.join(Topic) \
                         .on(Comment[:topic_id].eq(Topic[:topic_id])) \ 
                         .where(t[:topic_id].in(recent_unique_comments)) \
                         .order('comments.topic_id, comments.created_at DESC') \
                         .group_by(&:topic_id).to_a.map{|hsh| hsh[1][0]}
于 2010-08-24T09:55:31.957 回答
3

为了实现这一点,您需要有一个范围GROUP BY以获取每个主题的最新评论。然后,您可以订购此范围created_at以获取有关主题的最新评论。

以下适用于我使用 sqlite

class Comment < ActiveRecord::Base

  belongs_to :topic

  scope :recent, order("comments.created_at DESC")
  scope :latest_by_topic, group("comments.topic_id").order("comments.created_at DESC")
end


class Topic < ActiveRecord::Base
  has_many :comments

  scope :hot, joins(:comments) & Comment.latest_by_topic & limit(5)
end

我使用下面的seeds.rb 来生成测试数据

(1..10).each do |t|
  topic = Topic.new
  (1..10).each do |c|
    topic.comments.build(:subject => "Comment #{c} for topic #{t}")
  end
  topic.save
end

以下是测试结果

ruby-1.9.2-p0 > Topic.hot.map(&:id)
 => [10, 9, 8, 7, 6] 
ruby-1.9.2-p0 > Topic.first.comments.create(:subject => 'Topic 1 - New comment')
 => #<Comment id: 101, subject: "Topic 1 - New comment", topic_id: 1, content: nil, created_at: "2010-08-26 10:53:34", updated_at: "2010-08-26 10:53:34"> 
ruby-1.9.2-p0 > Topic.hot.map(&:id)
 => [1, 10, 9, 8, 7] 
ruby-1.9.2-p0 > 

为 sqlite(重新格式化)生成的 SQL 非常简单,我希望 Arel 能够为其他引擎呈现不同的 SQL,因为这在许多数据库引擎中肯定会失败,因为 Topic 中的列不在“按列表分组”中。如果这确实存在问题,那么您可以通过将选定的列限制为仅 comments.topic_id 来克服它

puts Topic.hot.to_sql
SELECT     "topics".* 
FROM       "topics" 
INNER JOIN "comments" ON "comments"."topic_id" = "topics"."id" 
GROUP BY  comments.topic_id 
ORDER BY  comments.created_at DESC LIMIT 5
于 2010-08-26T10:57:05.630 回答
2

由于问题是关于 Arel,我想我会添加这个,因为 Rails 3.2.1 添加uniq到 QueryMethods:

如果您添加.uniq到 Arel,它会添加DISTINCTselect语句中。

例如Topic.hot.uniq

也适用于范围:

例如scope :hot, joins(:comments).order("comments.created_at DESC").limit(5).uniq

所以我会假设

scope :hot, joins(:comments) & Comment.recent & limit(5) & uniq

也应该可以工作。

请参阅http://apidock.com/rails/ActiveRecord/QueryMethods/uniq

于 2012-04-03T16:09:45.183 回答