ruby on rails - Get last comments created -
there articles , comments.
the goal: list comments posted last on articles.
for example:
article #1 has 3 comments
article #2 has 1 comment
article #3 has no comments
goal: 2 comments created last on article #1, #2
class article < activerecord::base has_many :comments end class comment < activerecord::base belongs_to :article, counter_cache: true def self.last_comment # list comments created last on article end end class commentscontroller < applicationcontroller def last_comments @last_comments = comment.last_comment end end
one way cache last_comment_id
on article.
class article < activerecord::base has_many :comments, after_add: :update_last_comment, after_remove: :update_last_comment has_one :last_comment, class_name: "comment" private # process asynchronous job def update_last_comment self.last_comment = comments.order(created_at: :desc).first self.save! end end class comment < activerecord::base belongs_to :article, counter_cache: true def self.last_comment joins(:article). where("id = articles.last_comment_id") end end
the after_add
/after_remove
activerecord association callbacks, documented here.
Comments
Post a Comment