[RUBY] [Sort] Sort by following a user, following a follower, and following (descending order)!

Overview

A memorandum is recorded when a user is followed, followed, and sorted in the order of being followed (descending order).

environment

・ Ruby '2.5.7' ・ Rails '5.2.3'

Premise

-The user follow function has already been implemented.

【reference】 Chapter 14 Follow Users --Rails Tutorial

process

1. Confirmation of implementation

"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!

2. Define following and followers actions

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") ``.

result

Now you can sort the followers, followers, and followers in descending order!

Recommended Posts

[Sort] Sort by following a user, following a follower, and following (descending order)!
Sort List in descending order in Java and generate a new List non-destructively
Sort ArrayList by dragging and dropping ItemTouchHelper