How do I get the last user who created the last topic?

advertisements

i have 3 models as shown below. In my categories/index.erb.haml I have all the categories showing. I have a column that i want to show the latest topic that a user created and their name as well. I have an example below.

Category
  has_many :topics
Topic
  belongs_to :category
  belongs_to :user
User
  has_many :topics

.categories
- @categories.each do |category|
    .container
        .row
            .col-md-6
                .col-md-3
                    .img
                        = image_tag('first.png')
                .col-md-9
                    %h4.category.name
                        = link_to category.name, category_path(category)
                    %p
                        = category.description
            .col-md-2
                .topic-count
                    %h1
                        = category.topics.count
                .topics
                    Topics
            .col-md-4
                .description
                    %p
                        Last topic by 'user name here' Tue Nov 28, 2015
                        'topic title here'


If you want to get the last Topic for each Category than you have to loop through the Categories and get the last Topic since you have a relation.

Category.includes(:topics).find_each do |category|
  last_topic_of_the_category = category.topics.last  # <= The last topic
end