Skip to content
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

Allow filtering by scope #54

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/jsonapi/filtering.rb
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def jsonapi_filter_params(allowed_fields)
to_filter = to_filter.split(',')
end

if predicates.any? && (field_names - allowed_fields).empty?
if (field_names - allowed_fields).empty?
filtered[requested_field] = to_filter
end
end
Expand Down
8 changes: 7 additions & 1 deletion spec/dummy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@

class User < ActiveRecord::Base
has_many :notes

scope :created_before, ->(date) { where('created_at < ?', date) }

def self.ransackable_scopes(_auth_object = nil)
[:created_before]
end
end

class Note < ActiveRecord::Base
Expand Down Expand Up @@ -83,7 +89,7 @@ class UsersController < ActionController::Base
def index
allowed_fields = [
:first_name, :last_name, :created_at,
:notes_created_at, :notes_quantity
:notes_created_at, :notes_quantity, :created_before
]
options = { sort_with_expressions: true }

Expand Down
23 changes: 23 additions & 0 deletions spec/filtering_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,29 @@
expect(response_json['data'][0]).to have_id(second_user.id.to_s)
end
end

context 'returns users filtered by scope' do
let(:params) do
third_user.update(created_at: '2013-01-01')

{
filter: { created_before: '2013-02-01' }
}
end

fit 'ensures ransack scopes are working properly' do
ransack = User.ransack({ created_before: '2013-02-01' })
expected_sql = 'SELECT "users".* FROM "users" WHERE '\
'(created_at < \'2013-02-01\')'
expect(ransack.result.to_sql).to eq(expected_sql)
end

fit 'should return only' do
expect(response).to have_http_status(:ok)
expect(response_json['data'].size).to eq(1)
expect(response_json['data'][0]).to have_id(third_user.id.to_s)
end
end
end
end
end