【问题标题】:Sort by latest created comment按最新创建的评论排序
【发布时间】:2013-02-18 17:50:26
【问题描述】:

我在我的主题表中创建了一个 "active" 字段,我可以使用它来显示 活动主题,该字段将首先包含主题已创建,当有人 cmet 时,它将使用 comment.created_at 时间并将其放在主题表的活动字段中,就像任何其他论坛系统一样。

我在这里发现了类似的问题 How to order by the date of the last comment and sort by last created otherwise?

但它对我不起作用,我不知道为什么它不起作用。而且我也不明白在这种情况下是否需要使用 counter_cache 。我为我的 cmets 使用多态关联,因此我不确定如何使用 counter_cache。它在我的主题表中工作正常,可以将 created_at 时间复制到活动字段。但是当我创建评论时它不会起作用。

错误:

NoMethodError in CommentsController#create

未定义的方法“主题”用于

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

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

【问题讨论】:

  • 为什么要将Commentcreated_at 设置为activeTopic 值?您不想将topic.active 设置为Commentcreated_at 吗?
  • self.topic.active = self.created_at if self.topic, 试过这个我仍然得到同样的错误“未定义的方法 `topic' for #<0x000000047bc858>

标签: ruby-on-rails ruby-on-rails-3 comments


【解决方案1】:

没有意识到您使用的是多态关联。使用以下内容:

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

应该做的伎俩。

【讨论】:

  • 这不会产生错误,但不会更新活动字段·您编辑之前拥有的一个和现在拥有的一个。
  • 糟糕,忘记添加save!
猜你喜欢
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多