LoginSignup
0
1

More than 5 years have passed since last update.

railsで中間テーブルから配列を取ってリストを作る方法

Posted at

この記事の目的

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)で配列に変更してから変数に代入する。

0
1
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
1