stas / jsonapi.rb

Lightweight, simple and maintained JSON:API support for your next Ruby HTTP API.
MIT License
262 stars 58 forks source link

Ransackable scopes #57

Open stas opened 3 years ago

stas commented 3 years ago

What is the current behavior?

ActiveRecord scopes can't be used in filters. This supersedes the #54

What is the new behavior?

You can use scopes for filtering as well, to enable scopes, use the option flags:

options = { allowed_scopes: User.ransackable_scopes }
jsonapi_filter(User.all, [:created_before], options) do |filtered|
  render jsonapi: result.group('id').to_a
end

Assuming your model User has the following scope defined:

class User < ActiveRecord::Base
  scope :created_before, ->(date) { where('created_at < ?', date) }
  def self.ransackable_scopes(_auth_object = nil)
    [:created_before]
  end
end

This allows you to run queries like:

$ curl -X GET /api/resources?filter[created_before]='2021-01-29'

Checklist

Please make sure the following requirements are complete:

curtis741 commented 1 year ago

Any updates on this idea?

Was just trying to do this today.

tvdeyen commented 1 year ago

@stas we really would like to have this. Is there anything we can do to make it happen? Happy to contribute. I actually know @mamhoff personally and we work on the same app :)

barberj commented 1 year ago

Also just ran into this

BenAkroyd commented 1 year ago

Dealing with this now, nice solution!

stas commented 1 year ago

I'll have to make it backwards compatible, but definitely could have it released by next week. Ty ty for bringing it all up!

fastfedora commented 1 year ago

Checking in on this status as well. Any updates?