In order to customize this xml, I used as a starting point this stackoverflow post. For this purpose I have created a simple Rails application using scaffolding (employees) with a single database table that is a list of employees with the following 4 fields: age, category, family name and given name). In order to customize the XML when the user types http://localhost:3000/employees/1.xml (for instance), do the following:
- Create a builder template that is called, for instance, show.builder, this template is the one that will be used to show the database entry (in my sample application it would be (http://0.0.0.0:3000/employees/1.xml). The code of this template is the following (tags are in spanish):
xml.instruct!
xml.employee do
xml.nombre(@employee.given_name)
xml.apellido(@employee.family_name)
xml.edad(@employee.age)
xml.categoria(@employee.category)
end - In the controller (in my case employee_controller) I had to substitute the line
format.xml { render :xml => @employee }
by the line
format.xml { @employee }
Otherwise the application will render the XML in the default mode. If you still want to keep the default XML format, you can always redirect the rendering using the routes.cb configuration file.
format.xml { @employee }
by
format.xml do
stream = render_to_string(:template=>"employees/show.builder" )
send_data(stream, :type=>"text/xml",:filename => "test.xml")
end
This way, the Rails application renders the template and places it in stream and afterwards send this data into the test.xml file.
That's it!
Nice post ! Thanks for sharing valuable information with us. Keep sharing.. Ruby on Rails Online Course India
ReplyDelete