stas/jsonapi.rb

Filter not working

carlosjpr-collab opened this issue ยท 6 comments

I am using this url http://localhost:3000/api/v2/posts?filter[id]=1.

But its retrun all posts in my database.

I have defind @allowed_filtered_fields = %i[id number]

And i have this code that excute at the end but filtered.result retrun all resources

     jsonapi_filter(@resources, @allowed_filtered_fields) do |filtered|
          @resource_count = filtered.result.count
          jsonapi_paginate(filtered.result) do |paginated|
            render jsonapi: paginated
          end
        end

I also noted that the output of jsonapi_filter_params function is {}

Any help please ?

  • Version: 1.7
  • Ruby version: 2.7.2
  • Rails 6.0.3
stas commented

Thanks @carlosjpr-collab

Would you be kind to provide an example of the actual HTTP request with the params. Just to make it clear, filters won't apply if the filter param syntax is wrong (based off Ransack) or if the attributes of the item from the @resources are not id or number.

Again, I'm leaning more towards the fact that there's some misconfiguration on your end, since the testsuite covers filtering pretty thoroughly:
https://github.com/stas/jsonapi.rb/blob/master/spec/filtering_spec.rb#L43-L57

Hi @carlosjpr-collab, have you tried http://localhost:3000/api/v2/posts?filter[id_eq]=1? This flummoxed me for a while too.

stas commented

Closing this for now, @carlosjpr-collab feel free to reopen if it's still an issue ๐Ÿ™‡

Hi @carlosjpr-collab, have you tried http://localhost:3000/api/v2/posts?filter[id_eq]=1? This flummoxed me for a while too.

Thanks a lot. This had driven me crazy until I found your answer... I am wondering why it is not mentioned in the gem's official doc

stas commented

Thanks a lot. This had driven me crazy until I found your answer... I am wondering why it is not mentioned in the gem's official doc

@tien-do-hanko it is mentioned here: https://github.com/stas/jsonapi.rb#filtering-and-sorting

Just click on the Ransack link, it's a direct link to the search matchers. Ransack is a beast, I don't think it's a good idea to document every aspect of it. Basically, anything Ransack can do, is also possible via the filters support of this gem, and it's plenty ๐Ÿ˜ณ

stas commented

Also sorry for not making it obvious, please feel free to leave suggestions or PRs ๐Ÿ™‡