Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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