获取最后的评论

时间:2015-04-14 21:05:11

标签: ruby-on-rails

有文章和评论。

目标:列出所有文章最后发布的所有评论。

例如:

  

文章#1有3条评论

     

文章#2有1条评论

     

第3条没有评论

     
     

目标:获取最后在文章#1,#2

上创建的2条评论
class Article < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :article, counter_cache: true

 def self.last_comment
   # list all comments which are created last on any article
 end
end


class CommentsController < ApplicationController

def last_comments
  @last_comments = Comment.last_comment
end

end

2 个答案:

答案 0 :(得分:1)

以下是你的工作,但在我看来并不是一个好的解决方案:

class Article < ActiveRecord::Base
  has_many :comments
  def last_comment
    comments.last
  end
end


class Comment < ActiveRecord::Base
  belongs_to :article, counter_cache: true

 def self.last_comment
   Article.all.each_with_object([]) { |a, last_comments| last_comments << a.last_comment }
 end
end

现在你可以得到所有最后的评论:

Comment.last_comment

特定文章的最后评论:

@article.last_comment

答案 1 :(得分:1)

执行此操作的一种方法是在文章上缓存last_comment_id

class Article < ActiveRecord::Base
  has_many :comments, after_add: :update_last_comment, after_remove: :update_last_comment
  has_one :last_comment, class_name: "Comment"

  private

  # could process this as an asynchronous job
  def update_last_comment
    self.last_comment = comments.order(created_at: :desc).first
    self.save!
  end
end

class Comment < ActiveRecord::Base
  belongs_to :article, counter_cache: true

  def self.last_comment
    joins(:article).
      where("id = articles.last_comment_id")
  end
end

after_add / after_remove是ActiveRecord关联回调,记录为here