What is the correct way of handling custom XML responses in Rails 3.1?
In Rails 2 I had the following action in my controller:
# GET the blog as a feed
def feed
@blog = Blog.find(:first, :id => params[:id]])
@blog_id = @blog.id
@blog_posts = BlogPost.find(:all, :conditions => ["blog_id = ? AND is_complete = ?", @blog_id, true], :order => "blog_posts.created_at DESC", :limit => 15)
render :action => :feed, :layout => false
end
And then a RXML builder template in the view, 'feed.rxml':
xml.instruct! :xml, :version=>"1.0"
xml.rss(:version=>"2.0") {
xml.channel {
xml.title(@blog.title)
xml.link(url_for(:only_path => false))
xml.description(@blog.subtitle)
xml.language('en-us')
for blog_post in @blog_posts
xml.item do
xml.title(blog_post.title || '')
xml.link(blog_named_link(blog_post))
xml.description(blog_post.body)
xml.tag(blog_post.tag_string)
xml.posted_by(blog_post.posted_by.name)
end
end
}
}
Rails 3.1 has eliminated the RXML template handler but I can't seem to find documentation on what we should replace it with.
First add respond_to
section to your action method
respond_to do |format|
format.xml
end
or just add respond_to :html, :xml
inside controller class definition
Then rename the template file to feed.xml.builder
ShiningRay's answer was almost 100% for me, but I had to also force it to not render the default layout in order to make the xml valid.
# force this to render as xml - this method *only* does xml
request.format = "xml"
respond_to do |format|
format.xml {render :layout => false}
end
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