Skip to content

Instantly share code, notes, and snippets.

@IgnusG
Last active August 25, 2016 16:05
Show Gist options
  • Save IgnusG/39d12f7d2a475827330ded7521e52ad4 to your computer and use it in GitHub Desktop.
Save IgnusG/39d12f7d2a475827330ded7521e52ad4 to your computer and use it in GitHub Desktop.
Will map through all associations defined on a rails model and collect the result of a shared method
klas = item_type.constantize
has_many_associations = klas.reflections.collect { |_, c| c.class_name if c.macro == :has_many }.compact
has_one_associations = klas.reflections.collect { |_, c| c.class_name if c.macro == :has_one }.compact
instance = klas.find item_id
@result = instance.some_method
has_one_associations.each do |assoc_string|
assoc_string = assoc_string.underscore
if instance.respond_to? assoc_string
assoc = instance.send(assoc_string)
if assoc.respond_to?(:some_method) && !assoc.nil?
@result += assoc.some_method
end
end
end
has_many_associations.each do |assoc_string|
assoc_string = assoc_string.pluralize.underscore
if instance.respond_to? assoc_string
instance.send(assoc_string).each do |assoc|
if assoc.respond_to?(:some_method) && !assoc.nil?
@result += assoc.some_method
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment