我在这样的关系中有一个共同的模型:
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
。
哪种方法最简单,性能最快?
答案 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