2013-07-18 14 views
27

In questo momento ho questa linea:Includere modello associato durante il rendering JSON in Rails

render json: @programs, :except => [:created_at, :updated_at] 

Tuttavia, dal momento che un programma belongs_to una società vorrei mostrare il nome dell'azienda al posto della Società Id.

Come posso includere il nome dell'azienda durante il rendering dei programmi?

+0

Possiamo vedere il modello? –

+0

possibile duplicato: http://stackoverflow.com/questions/7506089/how-to-get-full-belongs-to-object-in-json-render –

risposta

43

Qualcosa del genere dovrebbe funzionare:

render :json => @programs, :include => {:insurer => {:only => :name}}, :except => [:created_at, :updated_at] 
+2

Ancora non capisco ... nessuna documentazione su come Fai questo? – Meekohi

8

considerare l'utilizzo di jbuilder per includere modelli nidificati in modo gestibile:

# /views/shops/index.json.jbuilder 
json.shops @shops do |shop| 

    # shop attributes to json 
    json.id shop.id 
    json.address shop.address 

    # Nested products 
    json.products shop.products do |product| 
    json.name product.name 
    json.price product.price 
    end 

end 
5

Si può anche fare questo a livello di modello.

program.rb

def as_json(options={}) 
    super(:except => [:created_at, :updated_at] 
      :include => { 
      :company => {:only => [:name]} 
      } 
    ) 
    end 
end 

Ora nel controller:

render json: @programs 
2

Prova questa. Ref

#`includes` caches all the companies for each program (eager loading) 
programs = Program.includes(:company) 

#`.as_json` creates a hash containing all programs 
#`include` adds a key `company` to each program 
#and sets the value as an array of the program's companies 
#Note: you can exclude certain fields with `only` or `except` 
render json: programs.as_json(include: :company, only: [:name]) 

Inoltre, non c'è bisogno di fare @programs una variabile di istanza, come io sto assumendo non stiamo passando a una vista.

8

stavo ottenendo lo stesso errore "non è possibile clonare il file Symbol" durante il rendering di json con include da un metodo controller. evitato in questo modo:

render :json => @list.to_json(:include => [:tasks]) 
0
#includes is used to avoid n+1 query. 
# http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations 
Here is an example for the above example.Lets say you have posts and each post has many comments to it. 

    @posts = Post.where('id IN [1,2,3,4]').includes(:comments) 
    respond_to do |format| 
    format.json {render json: @posts.to_json(:include => [:comments]) } 
    end 

    #output data 
    [ 
    {id:1,name:"post1",comments:{user_id:1,message:"nice"}} 
    {id:2,name:"post2",comments:{user_id:2,message:"okok"}} 
    {id:3,name:"post1",comments:{user_id:12,message:"great"}} 
    {id:4,name:"post1",comments:{user_id:45,message:"good enough"}} 
    ] 
+0

Penso che intendevi usare una virgola: '@posts, include:: comments'. Credo che otterrete un errore se provate ad eseguire i post come una funzione con parametri, ad esempio '@posts (' – Marklar

+0

grazie marklar, ma il codice sopra funzionerà. – user3716986

+0

Posso vedere che avete modificato il codice per includere 'to_json', quindi presumo è per questo che ora funziona e il vecchio codice di '@posts (: include => [: comments])' non ha funzionato? – Marklar

Problemi correlati