I have a controller that returns XML for a has_many
association in the most straight-forward but inefficient way possible:
@atoms = @molecule.atoms.find(:all, :include => :neutrons)
render :xml => @atoms.to_xml(:root => 'atoms')
This fetches and instantiates all objects at once. To make this more memory efficient I'd like to use ActiveRecord's batched find. At first glance, this seems to be the only way to do it:
xml = '<atoms>'
@molecule.atoms.find_each(:include => :neutrons) do |atom|
xml << atom.to_xml
end
xml << '</atoms>'
render :xml => xml
This is definitely more memory efficient but is decidedly less elegant. It duplicates some of the existing functionality of Array#to_xml
.
Is there a way to harness the power of find_each
without building XML by hand?