2013-03-04 47 views
0

我已經創建了一個「活動」在我的主題表字段,我可以用它來顯示活躍的主題,其中將包含在第一時間的主題是創建和當有人評論它將使用comment.created_at時間並將其放置在主題表中的活動字段中,就像任何其他論壇系統一樣。排序方式最新創建的評論

我發現類似的問題在這裏 How to order by the date of the last comment and sort by last created otherwise?

,但它不會爲我工作,林不知道爲什麼它不會。而且我也不明白我是否需要在這種情況下使用counter_cache。即時通訊使用多態關聯我的意見,所以因此我不知道我將如何使用counter_cache。它可以在我的主題表中正常工作,將created_at時間複製到活動字段。但是,當我創建評論時,它不會工作。

錯誤:

NoMethodError在CommentsController#創建

未定義的方法`主題」爲

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 
+0

爲什麼要將'Comment'的'created_at'設置爲'Topic'的'active'值?你不想把'topic.active'設置爲'Comment'的'created_at'嗎? – 2013-03-04 15:31:10

+0

self.topic.active = self.created_at如果self.topic,試過這我仍然得到相同的錯誤「未定義的方法'主題'爲#<評論:0x000000047bc858>」 – Pierre 2013-03-04 15:33:48

回答

0

沒有意識到你正在使用多態關聯。使用以下內容:

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

應該這樣做。

+0

這並沒有創建一個錯誤,但不會更新活躍的領域·你編輯之前的一個和你現在擁有的一個。 – Pierre 2013-03-04 15:50:34

+0

糟糕,忘了添加'save!'。 – 2013-03-04 15:52:55