Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails format.xml render and pass multiple variables

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.

like image 493
Dwarfer Avatar asked Dec 13 '22 14:12

Dwarfer


1 Answers

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.)

like image 174
Jon Gauthier Avatar answered Dec 27 '22 04:12

Jon Gauthier