Rails 3.1 替换 RXML 模板生成器
在 Rails 3.1 中处理自定义 XML 响应的正确方法是什么?
在 Rails 2 中,我在控制器中进行了以下操作:
# 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
然后视图中的 RXML 构建器模板“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 已经消除了 RXML 模板处理程序,但我似乎找不到有关我们应该替换的内容的文档它与。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先将
respond_to
部分添加到您的操作方法中,或者仅在控制器类定义中添加
respond_to :html, :xml
然后将模板文件重命名为
feed.xml.builder< /代码>
First add
respond_to
section to your action methodor just add
respond_to :html, :xml
inside controller class definitionThen rename the template file to
feed.xml.builder
ShiningRay 的答案对我来说几乎是 100%,但我还必须强制它不渲染默认布局,以使 xml 有效。
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.