Ruby on Rails高级JSON序列化 [英] Ruby on Rails Advanced JSON Serialization
问题描述
我希望在Rails应用程序中通过JSON呈现所有文章的索引以及完整的文章,但是我在弄清楚如何做到这一点上遇到了一些麻烦.
I'm looking to render an index of all articles along with a full article via JSON in my rails app, but I'm having a little trouble figuring out how to do it.
现在是我的控制人:
if params[:id]
@article = Article.find(params[:id])
else
@article = Article.published.not_draft.by_recent.first
end
respond_to do |format|
format.js { render :json => @article.to_json(
:except => [ :created_at, :updated_at, :draft, :id, :publish ],
:include => {
:comments => {
:only => [:body]
}
}),
:callback => params[:callback]}
end
我想在响应中要做的是添加所有文章的索引,如下所示:
What I'd like to do in the response is add an index of all articles, like so:
@index = Article.find(:all, :select => 'id, title')
我能够做到的唯一方法是将索引和文章都放入哈希或数组中,然后将其放入JSON中.
The only way I've been able to do it, is put both the index and article into a hash or array and then put that to JSON.
@response = { :item => @article, :index => @index }
同时提供完整代码:
@index = Article.find(:all, :select => 'id, title')
if params[:id]
@article = Article.find(params[:id])
else
@article = Article.published.not_draft.by_recent.first
end
@response = { :item => @article, :index => @index }
respond_to do |format|
format.js { render :json => @response.to_json(), :callback => params[:callback]}
end
这很好,除非现在我不能指定:include
或:except
并使其正确呈现.
This would be fine, except now I cannot specify :include
or :except
and get it to render properly.
推荐答案
您会提示问题中的解决方案.您最有可能想要建立一个散列以呈现为JSON.现在,这样做的首选方法是为as_json方法提供一个实现. as_json提供了一种正式的方式,可以通过建立包含要编码的数据的散列来定制to_json输出.
You hint at the solution in your question. You most likely want to build up a hash to render to JSON. The preferred way of doing this now is by providing an implementation for the as_json method. as_json provides a formal means of customizing to_json output by building up a hash containing the data you wish to encode.
可以在乔纳森(Jonathan)上找到有关as_json和to_json交互方式的更彻底的方法.朱利安的网志.
这篇关于Ruby on Rails高级JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!