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

后端 未结 4 522
-上瘾入骨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:41

    Incase anyone is looking for an alternative solution for this, this is how I solved this in Rails 4.2:

    def observe
      @item = some_item
      @user = some_user
    
      respond_to do |format|
        format.js do
          serialized_item = ItemSerializer.new(@item).attributes
          serialized_user = UserSerializer.new(@user).attributes
          render :json => {
            :item => serialized_item, 
            :user => serialized_user
          }
        end
      end
    end
    

    This returns the serialized version of both objects as JSON, accessible via response.user and response.item.

提交回复
热议问题