Last active
February 16, 2023 19:26
-
-
Save tonymarklove/0b9e12a0f162d5fcbe63648e5f96bdc4 to your computer and use it in GitHub Desktop.
ActiveRecord pluck_to_hash - pluck Active Record attributes into a Ruby Hash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pluck all columns if given no arguments
Pluck selected columns
Alias the resulting hash key names, including computed values