Last active
June 20, 2020 18:37
-
-
Save dnstufff/fbd03534f9fa01d4c1c493d1cd343b06 to your computer and use it in GitHub Desktop.
Ruby pluck() wrapper to return key:value hash
This file contains 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
# app/models/application_record.rb | |
class ApplicationRecord < ActiveRecord::Base | |
self.abstract_class = true | |
# explanatory == short | |
# explanatory | |
def self.pluck_to_hash_expl(*column_names) | |
pluck(*column_names).map do |column_values| | |
column_names.zip(column_values).reduce({}) do |hash, value| | |
hash.merge(value[0].to_sym => value[1]) | |
end | |
end | |
end | |
# short | |
def self.pluck_to_hash(*column_names) | |
pluck(*column_names).map { |p| column_names.zip(p).to_h } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment