首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Ruby on Rails高级JSON序列化

Ruby on Rails高级JSON序列化
EN

Stack Overflow用户
提问于 2009-03-03 19:52:48
回答 6查看 35.8K关注 0票数 18

我希望在我的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

我希望在响应中添加所有文章的索引,如下所示:

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

我所能做到的唯一方法就是将索引和文章放入散列或数组中,然后将其放入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并让它正确呈现。

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/607873

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档