2009-12-22 89 views
1

我有一个控制器,它能够以最直接的,但低效的方式返回XML的has_many协会:生成XML使用批处理找到ActiveRecord关联

@atoms = @molecule.atoms.find(:all, :include => :neutrons) 

render :xml => @atoms.to_xml(:root => 'atoms') 

这将提取和一次实例化的所有对象。为了提高内存的使用效率,我想使用ActiveRecord的批量查找。乍一看,这似乎是做到这一点的唯一方法:

xml = '<atoms>' 
@molecule.atoms.find_each(:include => :neutrons) do |atom| 
    xml << atom.to_xml 
end 
xml << '</atoms>' 

render :xml => xml 

这肯定是更多的内存效率,但断然那么优雅。它复制了Array#to_xml的一些现有功能。

有没有办法在没有手动构建XML的情况下利用find_each的威力?

回答

0

我通常生成XML的方法是使用XML Builder模板。

#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 
} 
+0

啊,对。我已经忘记了这一点。但我想我的担心不在哪里做建筑(对此,这绝对是最好的方法),而是根本不管建筑。我更喜欢能够调用'.to_xml'的自包含特性,并且找到一种方法来交换在使用'.find_each'生成集合的XML时使用的'.each'。 – Ian 2009-12-24 17:20:07