Skip to content

Commit

Permalink
Resource Controller: Allow additional Ransack filters
Browse files Browse the repository at this point in the history
When using custom Ransack filters, this will allow combining them with
the pagination. Without this, we can only combine the one ransack field
we use for searching in the top bar.

See #2978 for context.
  • Loading branch information
mamhoff committed Aug 1, 2024
1 parent 18a0b09 commit 1e1ee41
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 4 deletions.
11 changes: 7 additions & 4 deletions app/controllers/alchemy/admin/resources_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -200,10 +200,7 @@ def search_filter_params
def common_search_filter_includes
search_filters = [
{
q: [
resource_handler.search_field_name,
:s
]
q: [:s] + permitted_ransack_search_fields
},
:tagged_with,
:page,
Expand All @@ -219,6 +216,12 @@ def common_search_filter_includes
search_filters
end

def permitted_ransack_search_fields
[
resource_handler.search_field_name
]
end

def items_per_page
cookies[:alchemy_items_per_page] =
params[:per_page] || cookies[:alchemy_items_per_page] || Alchemy::Config.get(:items_per_page)
Expand Down
6 changes: 6 additions & 0 deletions spec/dummy/app/models/event.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ class Event < ActiveRecord::Base
scope :future, -> { where("starts_at > ?", Date.tomorrow.at_midnight) }
scope :by_location_name, ->(name) { joins(:location).where(locations: { name: name }) }

def self.ransackable_attributes(*)
[
"name"
]
end

def self.alchemy_resource_relations
{
location: { attr_method: "name", attr_type: "string" },
Expand Down
16 changes: 16 additions & 0 deletions spec/features/admin/resources_integration_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,22 @@
expect(page).not_to have_content("yesterday")
end
end

it "can combine ransack queries and pagination", :js do
allow_any_instance_of(Admin::EventsController).to receive(:permitted_ransack_search_fields).and_return([:name_start])
stub_alchemy_config(:items_per_page, 1)

visit "/admin/events?q[name_start]=today"

select("4", from: "per_page")

within "div#archive_all table.list tbody" do
expect(page).to have_selector("tr", count: 2)
expect(page).to have_content("today 1")
expect(page).to have_content("today 2")
expect(page).not_to have_content("yesterday")
end
end
end
end

Expand Down

0 comments on commit 1e1ee41

Please sign in to comment.