LoginSignup
2
2

More than 5 years have passed since last update.

Rails3.2 ActiveRecord::Calculations#pluckを複数列で使える拡張

Last updated at Posted at 2012-04-03

pluckメソッドで指定列の配列を取得できますが、
複数列まとめて取得したかったので、
その際書いたコードです。
※拡張と書いてしまいましたが、別メソッドとして利用するコードとなっています。

使い方

Model.select("key1 AS k1, key2 AS k2").multi_pluck([:k1, :k2])

結果

[["k1の値", "k2の値"], ["k1の値", "k2の値"] ・・・]

拡張用コード

active_record_multipluck_extension.rb
module ActiveRecord
  module Calculations
    def multi_pluck(column_names)
      result = klass.connection.select_all(arel, nil, bind_values)
      return result.map do |attributes|
        column_names.map do |key|
          klass.initialize_attributes(attributes)[key.to_s]
        end
      end
    end
  end
end

こちらを参考にさせてもらいました。
https://github.com/jeroeningen/rails/commit/da91b0ae75635b540307c406863620db4073c688

2
2
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
2
2