jsonapi.rb icon indicating copy to clipboard operation
jsonapi.rb copied to clipboard

Ransackable scopes

Open stas opened this issue 4 years ago • 7 comments

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:

  • [x] Tests for the changes have been added (for bug fixes / features)
  • [x] Docs have been reviewed and added / updated if needed (for bug fixes / features)
  • [x] All automated checks pass (CI/CD)

stas avatar Aug 04 '21 16:08 stas

Any updates on this idea?

Was just trying to do this today.

curtis741 avatar Jan 27 '23 23:01 curtis741

@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 :)

tvdeyen avatar Feb 15 '23 17:02 tvdeyen

Also just ran into this

barberj avatar Feb 15 '23 17:02 barberj

Dealing with this now, nice solution!

BenAkroyd avatar Feb 16 '23 16:02 BenAkroyd

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

stas avatar Feb 16 '23 17:02 stas

Checking in on this status as well. Any updates?

fastfedora avatar May 16 '23 18:05 fastfedora