Rails3: take control of the generated JSON (to_json with ORM with data)

From my Rails 3 application, I want JSON like this: {Quantity: 10, pictures: [{ID: 1}, ...]} I tried

render( :json => { :count => 10, :pictures => @pictures.to_json(:only=>:id) } )

but in this case my pictures are screened

..."pictures":"[{\"id\":2653299}, ....

In my old merb application, I had the following simple line in my controller:

    display( { :count=>@count, :pictures => @pictures } ) 

Since I use datamapperboth my ORM and dm-serializer, I'm not sure where to influence the generated json.

+3
source share
2 answers

Your code should be:

render( :json => {:count => 10, :pictures => @pictures })

without calling: to_json explicitly on @pictures (same as in merb app).

dm-1.0 : http://github.com/datamapper/dm-serializer/commit/64464a03b6d8485fbced0a5d7150be90b6dcaf2a

, , .

, : only = > [: id] . : as_json . . :

render( :json => {:count => 10, :pictures => @pictures.map {|p| p.as_json(:only => [:id])}} )

. , . ( )

0

"" . Rails 3 . - :

raw render( :json => { :count => 10, :pictures => @pictures.to_json(:only=>:id) } )

(, ):

render( :json => { :count => 10, :pictures => raw(@pictures.to_json(:only=>:id)) } )
0

Source: https://habr.com/ru/post/1765422/


All Articles