RubyonRails高级JSON序列化?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (26)

这里是我的控制器:

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

想在响应中添加一个所有文章的索引,如下所示:

@index = Article.find(:all, :select => 'id, title')

能够做到的唯一方法是将索引和文章都放入散列或数组中

@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
提问于
用户回答回答于

或者可以尝试下

...

@response = { :item => @article, :index => @index }

format.js { render :json => @response.to_json(
:except => {:item => [ :created_at, :updated_at, :draft, :id, :publish ]}, 
:include => { :item => {
        :comments => {
                :only => [:body]
        }
}}),
:callback => params[:callback]}
end
用户回答回答于

很可能想建立一个哈希来呈现给JSON。现在这样做的首选方法是为as_json

扫码关注云+社区

领取腾讯云代金券