Skip to content

Instantly share code, notes, and snippets.

@Chocksy
Created January 21, 2019 18:44
Show Gist options
  • Save Chocksy/7122230e0b07682ba9a2024aa7f8fa0e to your computer and use it in GitHub Desktop.
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.
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