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

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

    Working answer #2 To avoid the issue of your json being "escaped", build up the data structure by hand, then call to_json on it once. It can get a little wordy, but you can do it all in the controller, or abstract it out to the individual models as to_hash or something.

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

提交回复
热议问题