Order users based on when the relationship was cre

2019-09-06 12:51发布

问题:

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

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

回答1:

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"

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

Second Answer (when they're followed)

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