How to build a JSON response made up of multiple models in Rails

后端 未结 4 524
-上瘾入骨i
-上瘾入骨i 2020-12-28 20:33

First, the desired result

I have User and Item models. I\'d like to build a JSON response that looks like this:

{
  \"use         


        
4条回答
  •  不知归路
    2020-12-28 20:49

    EDITED to use as_json instead of to_json. See How to override to_json in Rails? for a detailed explanation. I think this is the best answer.

    You can render the JSON you want in the controller without the need for the helper model.

    def observe
      respond_to do |format|
        format.js do
          render :json => {
            :user => current_user.as_json(:only => [:username], :methods => [:foo, :bar]),
            :items => @items.collect{ |i| i.as_json(:only => [:id, :name], :methods => [:zim, :gir]) }
          }
        end
      end
    end
    

    Make sure ActiveRecord::Base.include_root_in_json is set to false or else you'll get a 'user' attribute inside of 'user'. Unfortunately, it looks like Arrays do not pass options down to each element, so the collect is necessary.

提交回复
热议问题