我真的很困惑如何在rails上的ruby中使用构建器模板.我有一些简单的控制器代码:
class ProductsController < ApplicationController
def index
@products = Product.all
respond_to do |format|
format.html # index.html.erb
format.xml # index.builder
end
end
end
Run Code Online (Sandbox Code Playgroud)
但这似乎不起作用.我的index.builder文件如下所示:
xm = Builder::XmlMarkup.new(:target=>$stdout, :indent=>2)
xm.instruct!
xm.index{
@index.each do |i|
xm.country(i.country.name)
xm.value(i.value)
xm.year(i.year)
end
}
Run Code Online (Sandbox Code Playgroud)
但我一直得到一个空白的回应.看起来我在这里不了解一些基本的东西.
重命名index.builder为index.xml.builder,然后在index.builder中已经可以使用xml对象,因此您可以将构建器文件调整为如下所示:
xml.instruct!
xml.posts do
@products.each do |product|
xml.product do
xml.title product.title
xml.body product.body
xml.price product.price
end
end
end
Run Code Online (Sandbox Code Playgroud)
更多信息:http://danengle.us/2009/05/generating-custom-xml-for-your-rails-app/