在rails中的respond_to块中传递多个参数

时间:2013-12-26 09:24:07

标签: ruby-on-rails

在我的line_items_controller中,我有以下代码

   format.xml  { render 'carts/_cart.html.erb',
                                 :status => :created, :location => @line_item }

我也需要在这里发送@cart。我试过这个

   format.xml  { render 'carts/_cart.html.erb', @cart,
                                 :status => :created, :location => @line_item }

但这不起作用。你能告诉我怎么做吗?

2 个答案:

答案 0 :(得分:1)

:location

相同
format.xml  { render 'carts/_cart.html.erb', :status => :created, :location => @line_item, :cart => @cart }

答案 1 :(得分:0)

尽管您尝试使用xml文件创建html响应,但您是否考虑过这个问题:

format.xml  { render :partial => 'carts/cart', :status => :created, :location => @line_item }
  

这应该在partial中处理@cart,因为@cart是一个实例var

respond_to区块的

Here is a more in-depth description,您可以从

中收集一些金块

我也为您找到了这个资源:Rails format.xml render and pass multiple variables。那里的史诗回复基本上建议您在函数中定义实例变量,然后在action.xml.erb文件中使用它们,如下所示:

#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>

这就是我现在所做的一切