Ruby on Rails Advanced JSON Serialization

前端 未结 7 950
闹比i
闹比i 2020-12-13 02:53

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.

Here

7条回答
  •  醉话见心
    2020-12-13 03:20

    Just to be clear the code above works with the :include and :except. And by works I mean it doesn't throw an error. The problem is it includes comments for every article in the index. I'm only looking to include comments for the :item and not any of the articles listed in the index.

    I couldn't get nesting to work as a hash or an OpenStruct object.

    Nesting on :include throws an error, nesting on :except doesn't throw an error, but nothing is filtered out, :created_at, etc. still show up.

    ...
    
    @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
    

提交回复
热议问题