Skip to content

Instantly share code, notes, and snippets.

@alyssais
Last active January 1, 2016 14:49
Show Gist options
  • Save alyssais/8160648 to your computer and use it in GitHub Desktop.
Save alyssais/8160648 to your computer and use it in GitHub Desktop.
Convert an ActiveRecord model into a hash structure with all associations.
class ActiveRecord::Base
def self.associations(exclude = [])
classes = Hash[reflect_on_all_associations.map do |association|
if (association.klass rescue nil)
association.as_json.values_at("name", "klass")
end
end.compact]
Hash[classes.map do |assoc_name, klass|
assocs = nil
assocs = klass.associations(exclude + [klass]) unless exclude.include? klass
[assoc_name, assocs]
end]
end
end
class Hash
def keyify(key, object = self)
return object unless object.is_a? Hash
{ key => Hash[object.map do |k, v|
[k, keyify(key, v)]
end] }
end
end
# simple example
Model.first.as_json(Model.associations.keyify(:include))
# previous example has terrible performance.
# objects should be eager-loaded.
assocs = Model.associations
Model.includes(assocs).first.as_json(assocs.keyify(:include))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment