简体   繁体   English

按最新创建的评论排序

[英]Sort by latest created comment

What i have created is a "active" field in my topics table which i can use to display the active topics , which will contain at first the time the topic was created and when someone comments it will use the comment.created_at time and put it in the active field in the topics table, like any other forum system. 我创建的是主题表中的“活动”字段,可用于显示活动主题 ,该字段将在创建主题时第一次包含,当有人发表评论时将使用comment.created_at并将其放入就像其他论坛系统一样,在主题表的活动字段中。

I found i similar question here How to order by the date of the last comment and sort by last created otherwise? 我在这里发现了类似的问题, 如何按最后评论的日期进行排序,以及按最后创建的日期进行排序?

But it wont work for me, im not sure why it wouldn't. 但这对我不起作用,我不确定为什么不起作用。 And i also don't understand if i need to use counter_cache in this case or not. 而且我也不明白在这种情况下是否需要使用counter_cache。 Im using a polymorphic association for my comments, so therefore im not sure how i would use counter_cache. 我使用我的评论的多态关联,因此我不确定我将如何使用counter_cache。 It works fine in my topic table to copy the created_at time to the active field. 在我的主题表中,它可以很好地将created_at时间复制到活动字段中。 But it wont work when i create a comment. 但是,当我创建评论时,它将不起作用。

Error: 错误:

NoMethodError in CommentsController#create CommentsController#create中的NoMethodError

undefined method `topic' for 未定义的方法“ topic”

Topic.rb Topic.rb

class Topic < ActiveRecord::Base
  attr_accessible :body, :forum_id, :title

  before_create :init_sort_column

  belongs_to :user
  belongs_to :forum
  validates :forum_id, :body, :title, presence: true

  has_many :comments, :as => :commentable

  default_scope order: 'topics.created_at DESC'

  private
  def init_sort_column
    self.active = self.created_at || Time.now
  end
end

Comment.rb Comment.rb

class Comment < ActiveRecord::Base
  attr_accessible :body, :commentable_id, :commentable_type, :user_id

  belongs_to :user
  belongs_to :commentable, :polymorphic => true

  before_create :update_parent_sort_column

  private

  def update_parent_sort_column
    self.topic.active = self.created_at if self.topic
  end

end

Didn't realise you were using a polymorphic association. 没意识到您正在使用多态关联。 Use the following: 使用以下内容:

def update_parent_sort_column
  commentable.active = created_at if commentable.is_a?(Topic)
  commentable.save!
end

Should do the trick. 应该做到的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM