Thibaud Clement
Thibaud Clement

Reputation: 6897

Rails 4: sorting items in chronological order in nested loop

In my Rails 4 app, I have the following models:

class User < ActiveRecord::Base
  has_many :administrations
  has_many :calendars, through: :administrations
end

class Calendar < ActiveRecord::Base
  has_many :administrations
  has_many :users, through: :administrations
  has_many :posts
  has_many :comments, through: :posts
end

class Administration < ActiveRecord::Base
  belongs_to :user
  belongs_to :calendar
end

class Post < ActiveRecord::Base
  belongs_to :calendar
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
  delegate :first_name, to: :user, prefix: true
end

In my Calendar#Index view, I needed to display a list of all the comments (from all posts and all calendars) of a user.

So, I updated my Calendar#Index controller as follows:

def index
  @user = current_user
  @calendars = @user.calendars.all
end

And, in my Calendar#Index view, I wrote the following code:

<table id="my_todo_table">

  <% @calendars.each do |calendar| %>

    <% calendar.comments.each do |comment| %>

      <tr>

        <td><span class="glyphicon glyphicon-calendar" aria-hidden="true"></span> <%= link_to calendar.name, calendar_path(calendar.id) %></td>
        <td><span class="glyphicon glyphicon-th-list" aria-hidden="true"></span> <%= comment.post.subject %> </td>
        <td><span class="glyphicon glyphicon-user" aria-hidden="true"></span> <%= comment.user.first_name %></td>
        <td><span class="glyphicon glyphicon-comment" aria-hidden="true"></span> <%= comment.body %></td>

      </tr>

    <% end %>

  <% end %>

</table>

This is working well, except for one small detail: currently, comments are sorted by calendars, and then by post (which makes sense, given the code above).

Instead, I would like to have them sorted in chronological order, ie the most recent first first, regardless of which calendar or post it belongs to.

Is there a way to achieve this?

Upvotes: 1

Views: 602

Answers (2)

Cyzanfar
Cyzanfar

Reputation: 7136

You could order by created_at datetime like so:

def index
  @user = current_user
  @calendars = Comment.where("user_id like ?", @user.id).order("created_at DESC")
end

Upvotes: 1

aaron.v
aaron.v

Reputation: 549

You could probably do a new ActiveRecord query for the comments, since you are getting the comments through calendars, I would do something like this.

@comments = Comment.joins(post: :calendar).where(calendars: {id: @calendars.pluck(:id)}).distinct.order(created_at: :desc)

This will find all the comments that belong to a calendar and order the comments according to the created_at time stamp

Upvotes: 1

Related Questions