【发布时间】: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
【问题讨论】:
-
为什么要将
Comment的created_at设置为active的Topic值?您不想将topic.active设置为Comment的created_at吗? -
self.topic.active = self.created_at if self.topic, 试过这个我仍然得到同样的错误“未定义的方法 `topic' for #<0x000000047bc858>0x000000047bc858>
标签: ruby-on-rails ruby-on-rails-3 comments