简体   繁体   中英

Passing multiple parameter in respond_to block in rails

In my line_items_controller in create action I have following code

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

I need to send @cart as well here. I tried this

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

But this is not working. Could you please tell me how to do this?

:location相同

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

Notwithstanding you're trying to create an xml response with an html file, have you considered this:

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

This should handle @cart in the partial, as @cart is an instance var

Here is a more in-depth description of the respond_to block which you may be able to glean some nuggets from

I also found this resource for you: Rails format.xml render and pass multiple variables . The epic reply on there basically suggests that you define your instance variables in your function, and then use them in the action.xml.erb file, like this:

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

That's all I got right now

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM