如何在Rails 3中自定义to_json响应 [英] How to customize to_json response in Rails 3
问题描述
我正在使用 respond_with
,所有内容都已正确连接以正确获取数据。我想自定义返回的 json
, xml
和 foobar
格式以DRY方式进行,但我无法弄清楚如何使用受限的:only
和:include
来实现此目的。当数据很简单时,这些功能非常有用,但是在发现复杂数据时,它们却达不到我想要的水平。
I am using respond_with
and everything is hooked up right to get data correctly. I want to customize the returned json
, xml
and foobar
formats in a DRY way, but I cannot figure out how to do so using the limited :only
and :include
. These are great when the data is simple, but with complex finds, they fall short of what I want.
让我说我有一个帖子, has_many
图片
Lets say I have a post which has_many
images
def show
@post = Post.find params[:id]
respond_with(@post)
end
我想包含图像响应,这样我就可以做到:
I want to include the images with the response so I could do this:
def show
@post = Post.find params[:id]
respond_with(@post, :include => :images)
end
但我真的不想发送整个图像对象,只是URL。除此之外,我真的也希望能够做类似的事情(伪代码):
but I dont really want to send the entire image object along, just the url. In addition to this, I really want to be able to do something like this as well (pseudocode):
def show
@post = Post.find params[:id]
respond_with(@post, :include => { :foo => @posts.each.really_cool_method } )
end
def index
@post = Post.find params[:id]
respond_with(@post, :include => { :foo => @post.really_cool_method } )
end
…但是全部以DRY方式进行。在较早的Rails项目中,我使用了XML构建器来定制输出,但是在看起来不正确的地方跨json,xml,html复制了它。我必须想象,Rails专家在Rails 3中添加了一些我没有意识到的行为。
… but all in a DRY way. In older rails projects, I have used XML builders to customize the output, but replicating it across json, xml, html whatever doesnt seem right. I have to imagine that the rails gurus put something in Rails 3 that I am not realizing for this type of behavior. Ideas?
推荐答案
这不是Rails 3的内置方式,但是我发现可以在Rails上积极维护的出色宝石3: acts_as_api
It is not the rails 3 built-in way, but I found a great gem that is actively maintained on Rails 3: acts_as_api
这篇关于如何在Rails 3中自定义to_json响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!