18 ruby serialization json ruby-on-rails xml-serialization
我想在我的rails应用程序中通过JSON呈现所有文章的索引以及完整的文章,但是我在弄清楚如何做到这一点时遇到了一些麻烦.
这是我的控制器:
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
Run Code Online (Sandbox Code Playgroud)
我想在响应中做的是添加所有文章的索引,如下所示:
@index = Article.find(:all, :select => 'id, title')
Run Code Online (Sandbox Code Playgroud)
我能够做到的唯一方法是将索引和文章放入哈希或数组中,然后将其放入JSON中.
@response = { :item => @article, :index => @index }
Run Code Online (Sandbox Code Playgroud)
两者的完整代码:
@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
Run Code Online (Sandbox Code Playgroud)
这没关系,除非现在我无法指定:include或:except让它正确渲染.
nir*_*rum 28
你暗示问题中的解决方案.您很可能希望构建一个哈希来呈现给JSON.现在这样做的首选方法是为as_json方法提供一个实现.as_json提供了一种通过构建包含要编码的数据的哈希来自定义to_json输出的正式方法.
有关as_json和to_json如何交互的更全面的处理可以在Jonathan Julian的博客上找到.
您应该能够像这样嵌套:include、等::except
:except => {:item => [ :created_at, :updated_at, :draft, :id, :publish ]}...
Run Code Online (Sandbox Code Playgroud)
如果这不起作用,请将其设为对象(例如 OpenStruct)而不是哈希。
——马库斯