根据关系的创建时间对用户排序_at [英] Order users based on when the relationship was created_at

查看:36
本文介绍了根据关系的创建时间对用户排序_at的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Railstutorials 创建关注者和 follow_users http://ruby.railstutorial.org/chapters/following-users#top

I used the Railstutorials to create followers and followed_users http://ruby.railstutorial.org/chapters/following-users#top

在我想显示特定人员的关注者/followed_users 的页面上,我想根据创建关系的时间显示他们.

On the page where I want to show a specific persons' followers/followed_users, I'd like to show them based on when the relationship was created.

@users = @user.followers.order("created_at DESC")

这样的 ^^ 只显示用户的创建时间,而不是关系的创建时间.如何有效地运行此查询以获得正确的排序?

Something like this ^^ just shows when the user was created, not when the relationship was created. How can I run this query efficiently to get the proper ordering?

def following
   @users = @user.followed_users
end

def followers
   @users = @user.followers
end

-User Model-

has_many :relationships, foreign_key: "follower_id", :dependent => :destroy
has_many :followed_users, through: :relationships, source: :followed
has_many :reverse_relationships, foreign_key: "followed_id",
                               class_name:  "Relationship",
                               dependent:   :destroy
has_many :followers, through: :reverse_relationships, source: :follower


- Relationship Model - 

belongs_to :follower, class_name: "User", touch: true
belongs_to :followed, class_name: "User", touch: true
validates :follower_id, presence: true
validates :followed_id, presence: true

推荐答案

由于您的用户有两个关系,您可以轻松地按照您想要的方向访问该表.

Since your user has there two relationships, you can easily access that table with the direction you want.

has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :reverse_relationships, foreign_key: "followed_id"

第一个回答(当他们是追随者时)

您必须使用 relationships 表,因为该记录会在您获得新关注者时创建,因此您可以这样做:

First Answer (when they're a follower)

You have to use the relationships table because that record gets created when you get a new follower, thus you do this:

@user.relationships.order("created_at DESC").collect { |r| User.find(r.followed) }

第二个答案(当他们被关注时)

@user.reverse_relationships.order("created_at DESC").collect { |r| User.find(r.follower) }

这篇关于根据关系的创建时间对用户排序_at的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆