Wesly
Wesly

Reputation: 343

How to get the date of the last comment a user created in a topic

I have a Topic model, Comment Model and a User model. They each have associations with each other. I want to see the date of the last comment that was commented in a uniq topic. I was thinking something like this would work but it just shows the last comment created by a user and not for each topic.

  = topic.user.comments.last.created_at.strftime("%b, %d, %Y")

  %table.table
            %thead
                %tr
                    %th Topic
                    %th Users
                    %th Replies
                    %th Activity
            - @topics.each do |topic|
                %tbody
                    %tr
                        %td{:width => "800"}
                            = link_to topic.title, topic_path(topic)
                        %td{:width => "200"}
                            .users-image
                                - topic.comments.uniq(&:user_id).each do |comment|
                                    = image_tag(comment.user.avatar.url(:thumb))
                        %td{:width => "80"}
                            .comments
                                = topic.comments.count
                        %td{:width => "80"}
                            .activity
                                =# topic.user.comments.last.created_at.strftime("%b, %d, %Y")

Comments table

create_table "comments", force: :cascade do |t|
 t.string   "commentable_type"
 t.integer  "commentable_id"
 t.integer  "user_id"
 t.text     "body"
 t.datetime "created_at",       null: false
 t.datetime "updated_at",       null: false
end

Upvotes: 0

Views: 138

Answers (1)

Yang
Yang

Reputation: 1923

Just use

topic.comments.last.created_at.strftime("%b, %d, %Y")

will get the last comment date of the topic.

Upvotes: 1

Related Questions