LoginSignup
0
0

More than 3 years have passed since last update.

【並び替え】あるユーザーのフォロー、フォロワーをフォローした、フォローされた順(降順)に並び替える!

Posted at

概要

あるユーザーのフォロー、フォロワーをフォローした、フォローされた順(降順)に並び替えた時のことを備忘録として記録します。

環境

・ruby '2.5.7'
・rails '5.2.3'

前提

・ユーザーのフォロー機能は実装済であること

【参考】
第14章 ユーザーをフォローする - Railsチュートリアル

過程

1.実装することの確認

「あるユーザー(@user)のフォロー、フォロワーを(@users)フォローした、フォローされた順(降順)に並び替える(order("relationships.created_at DESC"))」

これを具体的にコードにしていきます!

2.following,followersアクションを定義する

users_controllerにfollowing,followersアクションを定義していきます。

controllers/users_controller.rb
class UsersController < ApplicationController
(省略)

  def following
    @title = "フォロー"
    @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 = "フォロワー"
    @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

(省略)
end

コードを順番に説明していきます!(followingアクションのみ説明します)

① @user = User.find(params[:id])で表示されているユーザーを@userに代入します。

② get_follower_user_ids = Relationship.where(follower_id: @user.id).pluck(:followed_id)@userにフォローされているユーザーのidを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にフォローされているユーザーを@usersに代入します。

 ここで、includes(:passive_relationships)とすることで、Relationshipモデルを参照できるようになり、order("relationships.created_at DESC")で並び替えることができます。

結果

これで、あるユーザーのフォロー、フォロワーをフォローした、フォローされた順(降順)に並び替えることができました!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0