ruby-on-railsjsonapi-resources

How can I filter created_at by current year with JSONAPI::Resources?


I'm developing an Rails REST API using JSONAPI::Resources. And some resources, by default, must send only the records created in the current year, but it should also be possible for the client application to override this behavior in order to get older records.

I already tried to achieve this by creating this custom filter on the resources:

filter :current_year,
  apply: ->(records, value, _options) {
    if value[0] == 'true'
      records.where("date_part('year', created_at) = date_part('year', CURRENT_DATE)")
    else 
      records
    end
  }

But with this custom filter, the client application must always send the query string filter[current_year]=true on each request, and I don't want this to happen.

In short, the API should always filter the records by the current year, and the client application should be able to send a filter to get older records.

How can I do that?


Solution

  • I'm not so familiar with JSONAPI::Resources, but did you try adding default option?

    filter :current_year,
      default: 'true',
      apply: ->(records, value, _options) {
        if value[0] == 'true'
          records.where("date_part('year', created_at) = date_part('year', CURRENT_DATE)")
        else 
          records
        end
      }