Skip to content

Instantly share code, notes, and snippets.

@tonymarklove
Last active February 16, 2023 19:26
Show Gist options
  • Select an option

  • Save tonymarklove/0b9e12a0f162d5fcbe63648e5f96bdc4 to your computer and use it in GitHub Desktop.

Select an option

Save tonymarklove/0b9e12a0f162d5fcbe63648e5f96bdc4 to your computer and use it in GitHub Desktop.
ActiveRecord pluck_to_hash - pluck Active Record attributes into a Ruby Hash
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def self.pluck_to_hash(*column_names, **aliased_columns)
column_names = self.column_names.map(&:to_sym) if column_names.blank? && aliased_columns.blank?
columns_to_pluck = column_names + aliased_columns.values
keys = column_names + aliased_columns.keys
pluck(*columns_to_pluck).map do |row|
Hash[keys.zip(Array(row))]
end
end
end
@tonymarklove
Copy link
Author

Pluck all columns if given no arguments

> User.pluck_to_hash
=>
[{id: 2,
  email: "fred@example.com",
  created_at: Fri, 10 Feb 2023 11:29:06.615232000 UTC +00:00,
  updated_at: Wed, 15 Feb 2023 14:36:34.107862000 UTC +00:00,
  role: "admin",
  name: "Fred Dibnah"},
 {id: 1,
  email: "tony@example.com",
  created_at: Fri, 10 Feb 2023 11:29:06.615232000 UTC +00:00,
  updated_at: Thu, 16 Feb 2023 09:20:40.963285000 UTC +00:00,
  role: "superuser",
  name: "Tony Blackburn"}]

Pluck selected columns

> User.pluck_to_hash(:id, :email)
=> [{id: 2, email: "fred@example.com"}, {id: 1, email: "tony@example.com"}]

Alias the resulting hash key names, including computed values

> User.pluck_to_hash(full_name: :name, age_of_account: Arel.sql('now()::date - created_at::date'))
=> [{full_name: "Fred Dibnah", age_of_account: 6}, {full_name: "Tony Blackburn", age_of_account: 6}]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment