From 2d4ae4fb0eb23fe5f00fdb809f7d19b97c2cf798 Mon Sep 17 00:00:00 2001 From: Mattia Roccoberton Date: Mon, 11 Sep 2023 09:03:32 +0200 Subject: [PATCH] feat: ransack options support --- README.md | 15 +++++++++++++++ lib/administrate_ransack/searchable.rb | 3 ++- spec/controllers/admin/posts_controller_spec.rb | 8 ++++++++ .../app/controllers/admin/posts_controller.rb | 4 ++++ 4 files changed, 29 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index d469185..f38cc77 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,21 @@ end ## Customizations +- Ransack options can be customized defining a `ransack_options` method in the controller, example: + +```rb +module Admin + class PostsController < Admin::ApplicationController + prepend AdministrateRansack::Searchable + + def ransack_options + # raises exception on unknown parameters + { ignore_unknown_conditions: false } + end + end +end +``` + - Sample call of the filters partial with different options provided: ```erb diff --git a/lib/administrate_ransack/searchable.rb b/lib/administrate_ransack/searchable.rb index 2d12eed..17d89ef 100644 --- a/lib/administrate_ransack/searchable.rb +++ b/lib/administrate_ransack/searchable.rb @@ -5,7 +5,8 @@ module AdministrateRansack module Searchable def scoped_resource - @ransack_results = super.ransack(params[:q]) + options = respond_to?(:ransack_options) ? ransack_options : {} + @ransack_results = super.ransack(params[:q], **options) @ransack_results.result(distinct: true) end diff --git a/spec/controllers/admin/posts_controller_spec.rb b/spec/controllers/admin/posts_controller_spec.rb index 2bd7603..f55c360 100644 --- a/spec/controllers/admin/posts_controller_spec.rb +++ b/spec/controllers/admin/posts_controller_spec.rb @@ -7,5 +7,13 @@ expect(assigns(:ransack_results)).to be_instance_of Ransack::Search end + + context "when ransack_options is defined" do + it "raises an exception with an invalid parameter" do + expect { + get :index, params: { "q[title2_cont]" => "test" } + }.to raise_exception(ArgumentError, 'Invalid search term title2_cont') + end + end end end diff --git a/spec/dummy/app/controllers/admin/posts_controller.rb b/spec/dummy/app/controllers/admin/posts_controller.rb index d700bd8..f092785 100644 --- a/spec/dummy/app/controllers/admin/posts_controller.rb +++ b/spec/dummy/app/controllers/admin/posts_controller.rb @@ -2,6 +2,10 @@ module Admin class PostsController < Admin::ApplicationController prepend AdministrateRansack::Searchable + def ransack_options + { ignore_unknown_conditions: false } + end + # Overwrite any of the RESTful controller actions to implement custom behavior # For example, you may want to send an email after a foo is updated. #