Routing
Helper Methods
JR has a couple of helper methods available to assist you with setting up routes.
jsonapi_resources
Like resources
in ActionDispatch
, jsonapi_resources
provides resourceful routes mapping between HTTP verbs and URLs and controller actions. This will also setup mappings for relationship URLs for a resource’s relationships. For example:
Rails.application.routes.draw do |
gives the following routes
Prefix Verb URI Pattern Controller#Action |
jsonapi_resource
Like jsonapi_resources
, but for resources you lookup without an id. Resources used with this route should be marked as singleton
. See the Singlelton Resources section for more details.
Nested Routes
By default nested routes are created for getting related resources and manipulating relationships. You can control the nested routes by passing a block into jsonapi_resources
or jsonapi_resource
. An empty block will not create any nested routes. For example:
Rails.application.routes.draw do |
gives routes that are only related to the primary resource, and none for its relationships:
Prefix Verb URI Pattern Controller#Action |
To manually add in the nested routes you can use the jsonapi_links
, jsonapi_related_resources
and jsonapi_related_resource
inside the block. Or, you can add the default set of nested routes using the jsonapi_relationships
method. For example:
Rails.application.routes.draw do |
jsonapi_links
You can add relationship routes in with jsonapi_links
, for example:
Rails.application.routes.draw do |
Gives the following routes:
contact_relationships_phone_numbers GET /contacts/:contact_id/relationships/phone-numbers(.:format) contacts#show_relationship {:relationship=>"phone_numbers"} |
The new routes allow you to show, create and destroy the relationships between resources.
jsonapi_related_resources
Creates a nested route to GET the related has_many resources. For example:
Rails.application.routes.draw do |
gives the following routes:
Prefix Verb URI Pattern Controller#Action |
A single additional route was created to allow you GET the phone numbers through the contact.
jsonapi_related_resource
Like jsonapi_related_resources
, but for has_one related resources.
Rails.application.routes.draw do |
gives the following routes:
Prefix Verb URI Pattern Controller#Action |