Question

Suppose I have an Article with n Comments. How would I go about grabbing all the comments with the article in one query with DataMapper?

Something like the following false code:

Article.get(:id).include(:comments).to_json

I want the associated comments to be returned in the json like so:

{
  article object
  comments: [
    { comment object },
    { comment object } 
  ]
}

Seems like there must be a better way than grabbing the comments, and manually adding them to an attributes hash before calling to_json.

Was it helpful?

Solution

Found it on https://github.com/datamapper/dm-serializer in lib/to_json.rb

There are two options it seems, relationships and methods as options to the to_json method. Default inclusions are not yet possible, but requested:

@article.to_json(methods: [ :comments ])

To go deeper, there is an undocumented (so subject to change) example in a comment in the code is:

comments.to_json(:relationships=>{:user=>{:include=>[:first_name],:methods=>[:age]}})

So something like:

@article.to_json(relationships: { comments: { methods: [ :likes ] } }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top