Skip to content

Instantly share code, notes, and snippets.

@f0ster
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save f0ster/c0e0ca38346d6bfde019 to your computer and use it in GitHub Desktop.
Save f0ster/c0e0ca38346d6bfde019 to your computer and use it in GitHub Desktop.
def associations_attributes
# Get a list of symbols of the association names in this class
association_names = self.class.reflect_on_all_associations.collect { |r| r.name }
# Fetch myself again, but include all associations
me = self.class.find self.id, :include => association_names
# Collect an array of pairs, which we can use to build the hash we want
pairs = association_names.collect do |association_name|
# Get the association object(s)
object_or_array = me.send(association_name)
if(object_or_array.present?)
# Build the single pair for this association
if object_or_array.present? && object_or_array.to_a.respond_to?(:each)
# If this is a has_many or the like, use the same array-of-pairs trick
# to build a hash of "id => attributes"
association_pairs = object_or_array.collect { |o| [o.id, o.attributes] }
[association_name, Hash[*association_pairs.flatten(1)]]
elsif(object_or_array.present?)
# has_one, belongs_to, etc.
[association_name, object_or_array.attributes]
end
else
[association_name, nil]
end
end
# Build the final hash
Hash[*pairs.flatten(1)]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment