Ruby on Rails:如何通过中间模型字段进行排序?

时间:2018-07-14 10:59:53

标签: sql ruby-on-rails ruby ruby-on-rails-5

我在这样的关系中有一个共同的模型:

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

现在,我想订购

@diary.liked_users

来自likes.created_at

哪种方法最简单,性能最快?

1 个答案:

答案 0 :(得分:2)

简短答案

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

为什么行得通?

因此内部rails发出如下查询:

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

1仅是您要应用此方法的日记ID的示例。

这意味着查询中已经存在likes

因此,@diary.liked_users.order('likes.created_at ASC')会生成如下内容:

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