Created
February 25, 2014 16:49
-
-
Save ajvargo/9212840 to your computer and use it in GitHub Desktop.
Add in association attributes to model attributes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Based on http://stackoverflow.com/questions/2299139/retrieve-all-associations-attributes-of-an-ar-model | |
# Doesn't spelunk, doesn't name associations for easy consumption back. Good first go though. | |
# It gives the object attributes with the attributes of first cousin associations. | |
class ActiveRecord::Base | |
def attributes_with_associations | |
association_names = self.class.reflect_on_all_associations.collect { |r| r.name } | |
me = self.class.find self.id, :include => association_names | |
pairs = association_names.collect do |association_name| | |
object_or_array = me.send(association_name) | |
if object_or_array.nil? | |
[association_name, nil] | |
elsif object_or_array.is_a? Array | |
association_pairs = object_or_array.collect { |o| [o.id, o.attributes] } | |
[association_name, Hash[*association_pairs.flatten(1)]] | |
else | |
[association_name, object_or_array.attributes] | |
end | |
end | |
me.attributes.merge Hash[*pairs.flatten(1)] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment