🐢

Rubyのselectとfilter_mapの違い

2025/01/11に公開

これは何?

selectfilter_mapの具体的な動作の違いを示す

ユースケース

以下のモデルがあるとする(Railsガイドより)

Accountを持つSupplierを取得したい場合、selectを用いる:

my-rails-sandbox(dev)> Supplier.all.select(&:account)
  Supplier Load (0.2ms)  SELECT "suppliers".* FROM "suppliers" /*application='MyRailsSandbox'*/
  Account Load (0.1ms)  SELECT "accounts".* FROM "accounts" WHERE "accounts"."supplier_id" = 1 LIMIT 1 /*application='MyRailsSandbox'*/
=> 
[#<Supplier:0x00007fa6ba4fe3a0
  id: 1,
  name: nil,
  created_at: "2025-01-11 01:06:42.842598000 +0000",
  updated_at: "2025-01-11 01:06:42.842598000 +0000">]
my-rails-sandbox(dev)>

Supplierが持つAccountを取得したい場合、filter_mapを用いる:

my-rails-sandbox(dev)> Supplier.all.filter_map(&:account)
  Supplier Load (0.1ms)  SELECT "suppliers".* FROM "suppliers" /*application='MyRailsSandbox'*/
  Account Load (0.1ms)  SELECT "accounts".* FROM "accounts" WHERE "accounts"."supplier_id" = 1 LIMIT 1 /*application='MyRailsSandbox'*/
=> 
[#<Account:0x00007fa6ba4fd360
  id: 1,
  supplier_id: 1,
  account_number: nil,
  created_at: "2025-01-11 01:06:42.863186000 +0000",
  updated_at: "2025-01-11 01:06:42.863186000 +0000">]
my-rails-sandbox(dev)>

関連元を取得したいか、関連先を取得したいか、ニーズによって使い分けるとよい。

Discussion