我正在使用respond_with
并且一切都正确连接以正确获取数据。我想以 DRY 方式自定义返回的json
,xml
和foobar
格式,但我不知道如何使用有限的:only
and来实现:include
。当数据很简单时,这些很好,但是对于复杂的发现,它们达不到我想要的。
可以说我有一个has_many
图片的帖子
def show
@post = Post.find params[:id]
respond_with(@post)
end
我想在响应中包含图像,这样我就可以这样做:
def show
@post = Post.find params[:id]
respond_with(@post, :include => :images)
end
但我真的不想发送整个图像对象,只是 url。除此之外,我真的很希望能够做这样的事情(伪代码):
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
……但都是干的。在较旧的 Rails 项目中,我使用 XML 构建器来自定义输出,但在 json、xml、html 中复制它似乎不正确。我不得不想象 Rails 专家在 Rails 3 中添加了一些我没有意识到这种行为的东西。想法?