Domanda

Mi piacerebbe usare render: json ma sembra che non sia così flessibile. Qual è il modo giusto per farlo?

respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @things }

  #This is great
  format.json { render :text => @things.to_json(:include => :photos) }

  #This doesn't include photos
  format.json { render :json => @things, :include => :photos }
end
È stato utile?

Soluzione

Ho fatto qualcosa di simile con render: json . Questo è ciò che ha funzionato per me:

respond_to do |format|
    format.html # index.html.erb
    format.json  { render :json => @things.to_json(:include => { :photos => { :only => [:id, :url] } }) }
end

Altri suggerimenti

Immagino che questo articolo possa essere utile per te - Rails to_json o as_json? di Jonathan Julian.

Il pensiero principale è che dovresti evitare di usare to_json nei controller. È molto più flessibile definire il metodo as_json nel tuo modello.

Ad esempio:

Nel tuo modello Thing

def as_json(options={})
  super(:include => :photos)
end

E poi puoi scrivere nel tuo controller solo

render :json => @things

La gestione di hash complessi nei controller diventa brutta in fretta.

Con Rails 3, puoi utilizzare ActiveModel :: Serializer. Vedi http://api.rubyonrails.org/classes/ActiveModel/Serialization.html

Se stai facendo qualcosa di non banale, vedi https://github.com/rails-api/active_model_serializers . Ti consiglio di creare classi di serializzazione separate per evitare di ingombrare i tuoi modelli e rendere più semplici i test.

class ThingSerializer < ActiveModel::Serializer
  has_many :photos
  attributes :name, :whatever
end

# ThingsController
def index
  render :json => @things
end

# test it out
thing = Thing.new :name => "bob"
ThingSerializer.new(thing, nil).to_json
format.json { render @things.to_json(:include => :photos) }

in caso di array ciò che ho fatto è

respond_to do |format|
  format.html
  format.json {render :json => {:medias => @medias.to_json, :total => 13000, :time => 0.0001 }}
end
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top