Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save imjakechapman/45830dca58cd0e4b562c22e7f5cfab44 to your computer and use it in GitHub Desktop.

Select an option

Save imjakechapman/45830dca58cd0e4b562c22e7f5cfab44 to your computer and use it in GitHub Desktop.
Serializable Ruby Hash from an array of Rails objects that you need the hash key as object id and extra props
def methodToReturnHashMap
Hash[ self.some_method_that_returns_array_of_rails_objects.collect { |obj|
[obj.id , obj.attributes.merge({
extra: 'value',
another_extra: 'value'
})]
}]
end
##
## Then can be used on a model for json exposed to frontend.
## {
## json: <%= mymodel.methodToReturnHashMap.to_json %>
## }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment