Search code examples
jsonruby-on-rails-3datamapper

Rails3: Take control over generated JSON (to_json with datamapper ORM)


From my Rails 3 app i want a JSON like this: {count:10, pictures:[ {id:1}, ... ] } I tried

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

but in this case, my pictures get escaped

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

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

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

Because I am using datamapper as my ORM and dm-serializer I am not sure where to influence the generated json.


Solution

  • Your code should be:

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

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

    However, this will bomb in dm-1.0 without this commit: http://github.com/datamapper/dm-serializer/commit/64464a03b6d8485fbced0a5d7150be90b6dcaf2a

    I imagine it will be released soon, but in the meantime it's simple to patch.

    edit

    I overlooked the fact that you want to use :only => [:id] on your collection. It looks like :as_json has not been implemented on Collections for whatever reason. You can get around this in several ways. Your example might look like this:

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

    That will turn your Picture collection into a hash of IDs. render will then do its thang properly and you should get your desired results. (hopefully)