Taichi
Taichi

Reputation: 2587

Ruby on Rails: How to order by intermediate model's field?

I have a common models in relations like this:

user.rb

class User < ApplicationRecord
  has_many :likes

diary.rb

class Diary < ApplicationRecord
  has_many :likes
  has_many :liked_users, through: :likes, source: :user

like.rb

class Like < ApplicationRecord
  belongs_to :user
  belongs_to :diary

And now, I wanna order

@diary.liked_users

by likes.created_at .

What way is the most simplest, and fastest in performance ?

Upvotes: 1

Views: 69

Answers (1)

khaled_gomaa
khaled_gomaa

Reputation: 3412

Short answer

@diary.liked_users.order('likes.created_at ASC')

Why does this work?

So internally rails issues a query that looks like this:

Select users.* FROM like INNER JOIN users ON users.id = like.user_id WHERE like.diary_id = 1

1 here is just an example of the id of the diary you are applying this method on.

This means that likes table is already present in the query

Therefore @diary.liked_users.order('likes.created_at ASC') would generate something like this:

Select users.* FROM likes INNER JOIN users ON users.id = likes.user_id WHERE likes.diary_id = 1 ORDER BY likes.created_at ASC

Upvotes: 2

Related Questions