この記事の目的
railsでpostに申し込みをした人のリストを生成。
create_table "follow_users", force: :cascade do |t|
t.integer "follow_user_id"
t.integer "post_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "posts", force: :cascade do |t|
t.integer "user_id"
t.text "content"
t.text "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "provider"
t.string "uid"
t.string "nickname"
t.string "image_url"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
上記のような構成でfollow_usersが中間テーブルでここにpostと申込みを入れたユーザー(follow_user_id)が入っている。これを通してusersからnicknameを取ってくる。
pluckを使って配列を作成
post_controller.rb
def show
follow_user_list = FollowUser.where(post_id: @post.id)
follow_user_list_id = follow_user_list.pluck(:follow_user_id)
@follow_user = User.where(id: follow_user_list_id)
end
ただFollowUser.whereで取ってくると配列じゃないので@follow_user = User.where(id: follow_user_list_id)が通らない。なので.pluck(:follow_user_id)で配列に変更してから変数に代入する。