私が作成したのはトピックテーブルの「アクティブ」フィールドで、アクティブなトピックを表示するために使用できます。これには、最初にトピックが作成されたときに含まれ、誰かがコメントしたときにcomment.created_atを使用して配置します他のフォーラム システムと同様に、トピック テーブルのアクティブなフィールドに
ここで同様の質問を見つけまし た最後のコメントの日付で並べ替え、最後に作成された順に並べ替える方法は?
しかし、それは私にとってはうまくいきません。なぜうまくいかないのかわかりません。また、この場合 counter_cache を使用する必要があるかどうかもわかりません。コメントにポリモーフィックな関連付けを使用しているため、counter_cache の使用方法がわかりません。私のトピック テーブルでは、created_at 時刻をアクティブ フィールドにコピーすることで問題なく動作します。しかし、コメントを作成すると機能しません。
エラー:
CommentsController#create の NoMethodError
未定義のメソッド「トピック」
トピック.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
コメント.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