-
Notifications
You must be signed in to change notification settings - Fork 525
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Question] Advanced filtering - using "like" etc. - is it possible? #460
Comments
Post.collect do |post|
PostResource.new(post, context)
end or Post.collect do { |post| PostResource.new(post, context) } |
Answering 1) I think your question is less about the gem itself and more about the JSON API spec which the gem implements. I would posit that the Filter section of the JSON API Spec has the answer: that it's "agnostic about the [filtering] strategies supported by a server". So, you're likely correct: the spec doesn't require a standard methodology. In developing KnowPlace, we (@allthesignals and I) decided to implement a simple search via the |
Thank you for the quick response, I have missed the apply_filter funcionality, yes that is sufficient for all my needs. Thank you. |
@PavelJ If that fixed it for you, would you mind closing the issue? Thanks! :) |
If someone else wants to filter resources by using "like" searches, this is what I did:
|
I think it would be nice to use filters with predicates (like ransack does) class BaseResource < JSONAPI::Resource
abstract
def self.ransack_filter(name, opts = {})
opts[:apply] = ->(records, value, _options) do
records.ransack({name => value}).result
# or without ransack:
# records.public_send(name, value)
end
filter name, opts
end
def ransack_filters(*names)
options = names.extract_options!
names.each { |name| ransack_filter(name, options) }
end
class ProductResource < BaseResource
attribute :name
ransack_filters :name_equals, :name_contains
end
class Product < ActiveRecord::Base
# without ransack:
# scope :name_equals, ->(value) { where(name: value) }
# scope :name_contains, ->(value) { where('name LIKE ?', "%#{value}%") }
end |
Hi,
I just started looking at JSONAPI::Resources and I have some questions regarding filtering:
Is there any way to filter resource by using "like" searches? For example find all posts whose title contains a word "bird". It appears that there is no standard way to do it, at least I didn't find any.
If I want to use some complicated default filter in an "index" action for example, I was trying to use serializers - but I have no way how to easily serialize array of my records, what I mean is this:
render json:
This of course doesn't work - how can I easily convert a Relation or an array of records into an array of Resources? It looks like I have to iterate over each record and concert it mannualy.
Thank you for the answer.
The text was updated successfully, but these errors were encountered: