自身の投稿が重複して表示されてしまう
解決したいこと
Railsチュートリアルに沿ってsnsを制作しています。
フィードに自分自身の投稿とフォローしているユーザーの投稿を表示するのですが、
ユーザー自身の投稿が重複して表示されてしまいます。
なぜ重複するのか教えてください。
SELECT "microposts".* FROM "microposts"
LEFT OUTER JOIN "users" ON "users"."id" = "microposts"."user_id"
LEFT OUTER JOIN "relationships" ON "relationships"."followed_id" = "users"."id"
LEFT OUTER JOIN "users" "followers_users" ON "followers_users"."id" = "relationships"."follower_id"
WHERE (relationships.follower_id = 1 or microposts.user_id = 1)
ORDER BY "microposts"."created_at" DESC LIMIT ? OFFSET ? [["LIMIT", 30], ["OFFSET", 0]]
該当するソースコード
フォローしているユーザーと自身の投稿を取得するメソッド
def feed
part_of_feed = "relationships.follower_id = :id or microposts.user_id = :id"
Micropost.left_outer_joins(user: :followers)
.where(part_of_feed, { id: id })
.includes(:user, image_attachment: :blob)
end
userモデル
class User < ApplicationRecord
has_many :microposts, dependent: :destroy
has_many :active_relationships, class_name: "Relationship",
foreign_key: "follower_id",
dependent: :destroy
has_many :passive_relationships, class_name: "Relationship",
foreign_key: "followed_id",
dependent: :destroy
has_many :following, through: :active_relationships, source: :followed
has_many :followers, through: :passive_relationships, source: :follower
relationshipモデル
class Relationship < ApplicationRecord
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
micropostモデル
class Micropost < ApplicationRecord
belongs_to :user
has_one_attached :image do |attachable|
attachable.variant :display, resize_to_limit: [500, 500]
end
自分なりのコードの理解
外部結合によって
投稿・投稿者情報・フォロー関係を含む以下のような仮想テーブルが作成される
content | user_id | id | name | email | follwed_id | follower_id
(user_id, id, followed_idは同じ)
follower_id, user_id は ログインしているユーザーのidになる
よって
ログインユーザーがフォローしているユーザーの投稿
ログインユーザー自身の投稿
を取得できる
わからないこと
distinctがない場合、なぜログインしているユーザー自身の投稿が重複してしまうのか
0