I need to perform operations on all of a Rails 5 ActiveRecord object's associated objects, but I don't want to have to write a separate method call explicitly for each object.
For example, let's say "vacation" is the object I'm dealing with, and it could have many associated objects (let's assume all has_one for simplicity): agent, traveler, plane, ship, hotel.
I could do:
do_stuff_to_assoc_object(vacation.agent)
do_stuff_to_assoc_object(vacation.traveler)
do_stuff_to_assoc_object(vacation.plane) ...etc.
but that's very inelegant, especially if there are many associations. Thanks to How to get all the associated models from ActiveRecord object? , I know I can get the associated objects' model class names as strings, or the AssociationReflection object, but how how do I get the actual object they represent?
parent_object.reflect_on_all_associations(:has_one).map(&:class_name).each do |model_name|
### how to convert model_name into the object?
do_stuff_to_assoc_object(obj)
end
def do_stuff_to_assoc_object(obj)
# I do things to the associated object here
end