LoginSignup
3
0

More than 1 year has passed since last update.

【Rails】map関数で行うリファクタリング

Last updated at Posted at 2021-10-10

状況

UserテーブルとPostテーブルが1対1のアソシエーションの場合。
アクティブなUserの投稿した記事のidを配列形式で取得する

post_ids = User.where(status:"active").post.pluck(:id)

こんな感じで1行で取得したいが、User.where(status:"active")は配列なのでpostを一意に識別できずエラーになる

冗長なコード

users = User.where(status:"active")

post_ids = []
users.each do |user|
  post_ids.push(user.post)
end

あまりスタイリッシュじゃない、、。

map関数でリファクタリング

post_ids = User.where(status:"active").map { |u| u.post.id }

ワンラインで記載できていい感じ。

コメントを元に追記

下記でも取得できる。

User.where(status: 'active').joins(:posts).pluck('posts.id')

Another worksでは一緒に働ける仲間を探しています

3
0
4

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