【发布时间】:2010-09-15 15:13:15
【问题描述】:
我正在使用respond_with,并且所有内容都已正确连接以正确获取数据。我想以 DRY 方式自定义返回的 json、xml 和 foobar 格式,但我无法弄清楚如何使用有限的 :only 和 :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 中添加了一些我没有意识到这种行为的东西。想法?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 response dry respond-with