Rails format.xml渲染并传递多个变量

4

典型的使用方式是:

respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @users }
end

现在我还想传递一个名为“teststring”的字符串。

我看到过使用以下代码的参考:

:local => {:users => @users, :another => @another}

但是我不知道如何将它们合并在一起。我还没有看到所有的内容都放在一起的情况。目前没有太多关于该行中:xml的解释文档。而且我不知道我是否可以处理:teststring => teststring的字符串?
最后,既然我有了多个变量,现在该如何在我的index.html.erb中处理它们?它们是否要使用相同的名称从render命令中传递?
谢谢。
1个回答

13

如果您想呈现自定义XML,则需要在控制器的相应视图目录中创建一个index.xml.erb文件。它的使用方式与任何您想使用的HTML模板相同,如下所示:

app/controllers/home_controller.rb:

def index
    @users = ...
    @another = "Hello world!"

    # this `respond_to` block isn't necessary in this case -
    # Rails will detect the index.xml.erb file and render it
    # automatically for requests for XML
    respond_to do |format|
        format.html # index.html.erb
        format.xml # index.xml.erb
    end
end

app/views/home/index.xml.erb:

<?xml version="1.0" encoding="UTF-8"?>
<document>
    <%= @users.to_xml # serialize the @users variable %>
    <extra_string><%= @another %></extra_string>
</document>

(您可以在此处阅读有关ActiveRecord的to_xml方法的信息

我从中得到的提示是,首先我的字符串可以使用@stringname命名法。其次,变量名称确实会作为相同的传递。最后,在format.xml行上似乎不需要所有额外的信息,Rails知道该怎么做。 - Dwarfer
好的,谢谢你的提醒。我根据你最后的建议在代码中添加了一条注释。 - Jon Gauthier

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接