Heading image for post: ActiveRecord to JSON API Part 4: Custom Sorting

ActiveRecord to JSON API Part 4: Custom Sorting

Profile picture of Mary Lee

The JSONAPI::Resources automatically supported sorting on database fields, but didn’t handle custom sorting without requiring overrides to library methods.

Background

We were building an internal JSON API using the following libraries:

For more information on our goals and set up for the internal API, see part 1 of this series.

Custom Sorts

In a few of the ActiveRecord models we were converting, there were some custom sort methods that we needed to be able to specify through the API.

class LocalAPI::Foo < ApplicationRecord
  # …

  def self.abcs_last
    order("CASE foos.some_field WHEN 'abc' THEN 1 ELSE 0")
  end

  # … 
end

The JSONAPI::Resources automatically supported sorting on database fields, but in their documentation, they specify that any custom sorts require overriding the apply_sort method on the specific JSONAPI::Resource you’re working with.

# JSONAPI Resource
module LocalAPI
  class FooResource < BaseResource
    # …

    def self.apply_sort(records, order_options, context = {})
      if order_options.has_key?('abcs_last')
        records = records.abcs_last
        order_options.delete('abcs_last')
      end

      super(records, order_options, context)
    end

    # …
  end
end

With the ability to sort by our custom method, we then had to make sure the API allowed the method for sorting.

# JSONAPI Resource
module LocalAPI
  class FooResource < BaseResource
    # …

    def sortable_fields(_context)
      super + %i[abcs_last]
    end

    # … 
  end
end

We could then use the custom order with our JsonApiClient resources.

Closing Thoughts

This override process is well documented in the JSONAPI::Resource library, making it one of the most straightforward hurdles for us to overcome during the development process.

Check out the rest of this series!

  • Adobe logo
  • Barnes and noble logo
  • Aetna logo
  • Vanderbilt university logo
  • Ericsson logo

We're proud to have launched hundreds of products for clients such as LensRentals.com, Engine Yard, Verisign, ParkWhiz, and Regions Bank, to name a few.

Let's talk about your project