Super simple setup:
--api
and added the generator/frameworkname
attribute and a has_many
relationship to other Artefacts (boringly named .artefacts
)node1.artefacts = node2
)Now, when browsing to /artefacts
, the JSON returned is just the 2 nodes.
How can Rails return the relationships
and for down the road; how can Rails return a custom JSON layout such as:
[{"artefact":{"name":"Node1","id":"e6571172-889c-4dd9-abca-a522f28c970d", artefacts: ["0643d8c5-fc67-431c-b015-7c5894439058", "5e7ceb40-18da-474e-8fe0-22d3887943b4"]}}]
It all depends on how you're serializing. By default Rails will just serialize the node object. You should be able to use the include
option as suggested here for ActiveRecord
:
Include associated model when rendering JSON in Rails
I also personally like the json:api standard for serializing objects. One of the big advantages is that you can include associated objects and the objects are side-loaded efficiently so that you don't include duplicates in your responses. The other thing that I like about it is it's a standard, whereas when I've rendered JSON in apps in the past it's often been just whatever the developer working on that card thought was best.
The jsonapi-resources
gem is popular for this:
https://github.com/cerebris/jsonapi-resources
That gem takes care a lot of the Rails integration and creates controllers and routes for you, but there are some problems with the integration with ActiveNode
. I've used the jsonapi-serializers
gem with success, but it requires you to do some more things for yourself:
https://github.com/fotinakis/jsonapi-serializers
You might look at this Rails example of it:
https://github.com/fotinakis/jsonapi-serializers#rails-example