Created
January 21, 2019 18:44
-
-
Save Chocksy/7122230e0b07682ba9a2024aa7f8fa0e to your computer and use it in GitHub Desktop.
Add .pluck_to_hash to ActiveRecord. The result will get the columns specified as keys for the hash and their values.
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
module ActiveRecordPluckToHash | |
def pluck_to_hash(*keys) | |
formatted_keys = keys.map do |k| | |
"'#{k.to_s.split(/\b.\b/i)[-1].strip}', #{k}" | |
end.join(', ') | |
pluck(Arel.sql("json_build_object(#{formatted_keys})")).map(&:with_indifferent_access) | |
end | |
end | |
ActiveRecord::Relation.send :include, ActiveRecordPluckToHash | |
# Usage: Skill.where(id: 10).pluck_to_hash(:id, :name, :category) => [{'id' => 10, 'name' => 'HTML', 'category' => 'Programming'}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment