LoginSignup
12
8

More than 3 years have passed since last update.

【Rails】フォローしているユーザーの投稿をすべて取得する方法

Last updated at Posted at 2020-11-06

環境

  • ユーザー認証にgemdeviseを使用。
  • モデル間同志のアソシエーション済み。
    → 設計方法はこちらと同じ。

方法

フォローしているユーザーの全ての投稿を取得する方法

該当のcontroller
#フォローしているユーザーの投稿

@posts = Post.where(user_id: [*current_user.following_ids])

フォローしているユーザーと自分も含めた全ての投稿を取得する方法

該当のcontroller
#フォローしているユーザーと自分の投稿

@posts = Post.where(user_id: [current_user.id, *current_user.following_ids])

説明

  • following_ids
    → モデル間でアソシエーションが完了しているとRailsが自動生成してくれるメソッド
12
8
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
12
8