A memorandum is recorded when a user is followed, followed, and sorted in the order of being followed (descending order).
・ Ruby '2.5.7' ・ Rails '5.2.3'
-The user follow function has already been implemented.
【reference】 Chapter 14 Follow Users --Rails Tutorial
"Follow a user (" @ user), sort followers (` `@ users
) in the order they were followed (descending) ( ʻorder (" relationships.created_at DESC ")
`)"
Let's make this a concrete code!
Define following and followers actions in users_controller.
controllers/users_controller.rb
class UsersController < ApplicationController
(abridgement)
def following
@title = "Follow"
@user = User.find(params[:id])
get_follower_user_ids = Relationship.where(follower_id: @user.id).pluck(:followed_id)
@users = User.includes(:passive_relationships).where(id: get_follower_user_ids).order("relationships.created_at DESC").paginate(page: params[:page])
render 'show_follow'
end
def followers
@title = "Follower"
@user = User.find(params[:id])
get_followed_user_ids = Relationship.where(followed_id: @user.id).pluck(:follower_id)
@users = User.includes(:active_relationships).where(id: get_followed_user_ids).order("relationships.created_at DESC").paginate(page: params[:page])
render 'show_follow'
end
(abridgement)
end
I'll explain the code in order! (Only the following action will be explained)
① Substitute the user displayed in @ user = User.find (params [: id])
to @ user
.
② In get_follower_user_ids = Relationship.where (follower_id: @ user.id) .pluck (: followed_id)
, substitute the id of the user who is followed by @ user
into get_follower_user_ids
.
③ @users = User.includes (: passive_relationships) .where (id: get_follower_user_ids) .order ("relationships.created_at DESC"). Paginate (page: params [: page])
@user
Assign the users followed by to @ users
.
Here, you can refer to the Relationship model by setting ʻincludes (: passive_relationships)
, and you can sort by
ʻorder (" relations.created_at DESC") ``.
Now you can sort the followers, followers, and followers in descending order!