根据创建关系的时间为用户订购

时间:2014-03-05 01:54:17

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

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

在我想要显示特定人员的关注者/ follow_users的页面上,我想根据关系的创建时间显示它们。

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

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

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

1 个答案:

答案 0 :(得分:1)

由于您的用户有两种关系,因此您可以使用所需的方向轻松访问该表。

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

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

您必须使用relationships表,因为当您获得新关注者时会创建该记录,因此您执行此操作:

@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) }