Generating XML for ActiveRecord associations using batched find
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开发者_如何学C'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?
My usual approach to generating XML is to use the XML Builder template.
#in the controller
respond_to do |format|
format.html # index.html.erb
format.xml # index.xml.builder
end
#in index.xml.builder
xml.atoms {
@molecule.atoms.find_each(:include => :neutrons) do |atom|
#etc
end
}
精彩评论