Typical usage is:
respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @users }
end
And now I want to also pass a string named "teststring".
I've seen reference to using
:local => {:users => @users, :another => @another}
But I don't know how to merge the two together. I just haven't seen everything all together. Not much documentation to really explain the :xml in that line. And I don't know if I can deal with the string with :teststring => teststring?
And lastly, how do I deal with them in my index.html.erb now that I have multiple variables? Do they get passed with the same name from the render command?
Thanks.
If you want to render custom XML, you'll need to create a index.xml.erb file in the corresponding view directory for the controller. It works just like any HTML template you'd use, then:
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>
(You can read about ActiveRecord's to_xml method here.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With