我有一个奇怪的场景:我想在P的创建者和当前用户成为朋友之前订购所有帖子P.
结果将是在顶部的较新朋友帖子和底部的较老朋友帖子的帖子列表.我们可以假设所有用户都是所有其他用户的朋友,但每个友谊都有不同的创建时间.
我有Post,User和Friendship模型.帖子属于用户,用户有很多友谊.
class User < ActiveRecord::Base
has_many :friendships
has_many :friends, :through => :friendships
has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
has_many :inverse_friends, :through => :inverse_friendships, :source => :user
end
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, :class_name => "User"
end
class Post < ActiveRecord::Base
belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)
最好的方法是什么?谢谢!
Sea*_*ill 32
您可以通过嵌套连接在关联表上进行排序,如下所示:
@posts = Post.joins(:user => :friendships).order("friendships.friended_at")
Run Code Online (Sandbox Code Playgroud)
将肖恩希尔的答案变成一个范围:
class Post < ActiveRecord::Base
belongs_to :user
scope :ordered, -> {
joins(:user => :friendships).order("friendships.friended_at")
}
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12475 次 |
| 最近记录: |