From 31d4797a30a5e964f6eb0e15fe52f8e6097d7093 Mon Sep 17 00:00:00 2001 From: Denis Talakevich Date: Fri, 27 Nov 2026 20:24:21 +0200 Subject: [PATCH 1/5] Add a None option to select filters extensions: { none: true } adds a None choice that searches the attribute's _null. Only the search sees the rewrite, so defaults, policies and the redirect still read the request as submitted. Co-Authored-By: Clanker --- README.md | 35 ++++ config/locales/en.yml | 2 + lib/active_admin_filter_extensions.rb | 14 +- .../data_access.rb | 6 +- .../filter_defaults.rb | 12 +- .../filter_options.rb | 2 +- .../filters_form.rb | 58 +++++- .../none_option.rb | 115 ++++++++++++ .../policies.rb | 19 +- .../search_keys.rb | 3 +- spec/integration/none_option_spec.rb | 173 ++++++++++++++++++ spec/spec_helper.rb | 2 + spec/support/rails_template.rb | 44 ++++- 13 files changed, 467 insertions(+), 18 deletions(-) create mode 100644 lib/active_admin_filter_extensions/none_option.rb create mode 100644 spec/integration/none_option_spec.rb diff --git a/README.md b/README.md index 744264c..ea583e5 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,8 @@ filter :created_at, as: :date_time_range, floors on two-ended filters. * [`message:`](#value-policies-sanitize-and-validate) and plain-i18n defaults for every violation text. +* [`none:`](#none-option) - a None option on a select filter, for the records whose attribute + is empty. * [`default_filters_notice`](#telling-the-admin-why) - the flash that tells the admin why the page shows a slice; [`require_any_filter`](#resource-level-guard) - an index that waits to be asked. @@ -336,6 +338,39 @@ lands in `flash[:error]` (and rides the redirect), and the filter's declared `de any - refills through the ordinary merge. The defaults notice stays quiet on that render: the error already explains why the page shows the default slice. +## None option + +A select filter cannot ask for the records whose attribute is empty: no value of its collection +means that. `none:` adds the option, first in the list after the blank one: + +```ruby +filter :account, as: :select, collection: proc { Account.order(:name) }, extensions: { none: true } +filter :status, as: :select, multiple: true, collection: %w[draft published], + extensions: { none: "No status" } # the option's label +``` + +`true` labels the option from the i18n key `active_admin_filter_extensions.none` ("None"); a +String is the label itself. Picking it searches `_null` on the filter's attribute. On a multiple +select, None beside other values searches "any of these, or empty". + +The select submits a sentinel under its own key - `q[account_id_eq]=__none__` - and only the +search is handed the `_null` condition. The URL, the form and the other extensions read the +request as submitted: `required:` counts None as an answer, `sanitize:` and `validate:` are not +handed the sentinel, and `default: -> { ActiveAdminFilterExtensions.none_value }` opens the +index on the empty records. The Current Filters panel shows the label: "Account equals None". +Move the sentinel where a real value could spell the same thing: + +```ruby +ActiveAdminFilterExtensions.none_value = "__empty__" +``` + +Only a select that submits `_eq` or `_in` takes the option; `none:` on any other filter raises. + +A dependent select - the active_admin_theme searchable select with `depends_on:`, say - sends +its parent's value to its options endpoint, so that endpoint is sent the sentinel too. It is +applied there when the endpoint is an Active Admin index that declares the same filter with +`none:`. An endpoint that searches `q` on its own is handed the sentinel as a plain value. + ## The redirect A bare visit to the index redirects once to itself with the effective filters spelled out in diff --git a/config/locales/en.yml b/config/locales/en.yml index 403dc48..b53c537 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -8,3 +8,5 @@ en: before_floor: "%{filter} filter cannot start before %{floor}." given_together: "%{filters} filters must be given together." require_any_filter: "You must specify at least one filter" + # The label of a select filter's None option (`extensions: { none: true }`). + none: "None" diff --git a/lib/active_admin_filter_extensions.rb b/lib/active_admin_filter_extensions.rb index 5fd4522..a7dde67 100644 --- a/lib/active_admin_filter_extensions.rb +++ b/lib/active_admin_filter_extensions.rb @@ -12,6 +12,7 @@ require "active_admin_filter_extensions/search_keys" require "active_admin_filter_extensions/required_filters" require "active_admin_filter_extensions/filter_defaults" +require "active_admin_filter_extensions/none_option" require "active_admin_filter_extensions/filters_form" require "active_admin_filter_extensions/redirect" require "active_admin_filter_extensions/policies" @@ -33,6 +34,14 @@ def notice_flash_key @notice_flash_key ||= :notice end + # What the None option of a select filter submits (`extensions: { none: true }`). Move it + # where a real value of a filtered column could spell the same thing. + attr_writer :none_value + + def none_value + @none_value ||= "__none__" + end + # Active Admin 4 moved the filters form helper and the Current Filters section. def aa_v4? return @aa_v4 if defined?(@aa_v4) @@ -58,8 +67,10 @@ def warning_flash_key ActiveAdmin::ResourceController.include ActiveAdminFilterExtensions::SearchKeys ActiveAdmin::ResourceController.include ActiveAdminFilterExtensions::RequiredFilters ActiveAdmin::ResourceController.include ActiveAdminFilterExtensions::FilterDefaults + ActiveAdmin::ResourceController.include ActiveAdminFilterExtensions::NoneOption ActiveAdmin::ResourceController.helper_method :filtering_params, :applied_filter_params, - :filter_default_values, :visible_filters + :filter_default_values, :visible_filters, + :none_filter_form_options ActiveAdmin::ResourceDSL.include ActiveAdminFilterExtensions::Policies::ResourcePolicyDSL ActiveAdmin::Resource.include ActiveAdminFilterExtensions::Policies::ResourcePolicySettings @@ -69,6 +80,7 @@ def warning_flash_key # decision - and therefore the URL - is computed from. ActiveAdmin::ResourceController.include ActiveAdminFilterExtensions::Policies::Controller ActiveAdmin::ResourceController.include ActiveAdminFilterExtensions::Redirect + ActiveAdmin::Filters::Active.prepend ActiveAdminFilterExtensions::CurrentFilters if ActiveAdminFilterExtensions.aa_v4? ActiveAdmin::Resource.prepend ActiveAdminFilterExtensions::ResourceExtensionV4 ActiveAdmin::FormHelper.prepend ActiveAdminFilterExtensions::ViewHelper diff --git a/lib/active_admin_filter_extensions/data_access.rb b/lib/active_admin_filter_extensions/data_access.rb index feb3839..8722cf2 100644 --- a/lib/active_admin_filter_extensions/data_access.rb +++ b/lib/active_admin_filter_extensions/data_access.rb @@ -3,12 +3,14 @@ module ActiveAdminFilterExtensions # The single method this gem replaces: Active Admin searches the collection on `params[:q]` # read directly, and it searches #filtering_params instead. Everything that method means is - # in FilterDefaults. + # in FilterDefaults. A None option's sentinel becomes its `_null` condition here and no + # earlier - see NoneOption. module DataAccess protected def apply_filtering(chain) - @search = chain.ransack(filtering_params, **filter_ransack_options) + @search = chain.ransack(none_filter_search_params(filtering_params), **filter_ransack_options) + label_none_filters(@search) # An :empty policy keeps the request intact - the form still shows what the admin # typed - and blanks the collection instead. return @search.result.none if filter_policy_render_empty? diff --git a/lib/active_admin_filter_extensions/filter_defaults.rb b/lib/active_admin_filter_extensions/filter_defaults.rb index e08a271..61f3e2c 100644 --- a/lib/active_admin_filter_extensions/filter_defaults.rb +++ b/lib/active_admin_filter_extensions/filter_defaults.rb @@ -203,16 +203,18 @@ def validate_default_against_value_policies(attribute, options, result, keys) value = result[key] next if value.nil? + none = policy_exempt_none_value(attribute, options, key) + # Judged the way the URL will say it: a scalar as the String it becomes, an Array # element by element - the shape a multi-valued input submits. if sanitizer resolved = Policies::Sanitizers.resolve(sanitizer) - result[key] = sanitize_default_value(attribute, resolved, value) + result[key] = sanitize_default_value(attribute, resolved, value, none) end next unless validator resolved_validator = Policies::Validators.resolve(validator) - next unless default_value_strings(result[key]) + next unless (default_value_strings(result[key]) - [none]) .any? { |string| ::MethodOrProcHelper.render_in_context(self, resolved_validator, string) } raise ArgumentError, @@ -233,9 +235,9 @@ def default_value_strings(value) Array.wrap(value).map(&:to_s).reject(&:blank?) end - def sanitize_default_value(attribute, sanitizer, value) - return value.map { |element| sanitize_default_value(attribute, sanitizer, element) } if value.is_a?(Array) - return value if value.is_a?(Enumerable) + def sanitize_default_value(attribute, sanitizer, value, none = nil) + return value.map { |element| sanitize_default_value(attribute, sanitizer, element, none) } if value.is_a?(Array) + return value if value.is_a?(Enumerable) || value == none sanitized = ::MethodOrProcHelper.render_in_context(self, sanitizer, value.to_s.dup).to_s # The same fixpoint check submitted values face: without it the CSV searches the diff --git a/lib/active_admin_filter_extensions/filter_options.rb b/lib/active_admin_filter_extensions/filter_options.rb index 11b1a01..966e1aa 100644 --- a/lib/active_admin_filter_extensions/filter_options.rb +++ b/lib/active_admin_filter_extensions/filter_options.rb @@ -10,7 +10,7 @@ module FilterOptions # `:if` / `:unless` are Active Admin's but are resolved by #visible_filters before the # form is given anything. NOT_FOR_INPUT = %i[extensions if unless].freeze - EXTENSION_KEYS = %i[default required with sanitize validate on_invalid max_range min message].freeze + EXTENSION_KEYS = %i[default required with sanitize validate on_invalid max_range min message none].freeze # required: and min: are documented Formtastic input options in their own right. The gem # answers to them only INSIDE extensions:, so flat they are the host's: no stray-key raise, # no policy, straight through to the input. diff --git a/lib/active_admin_filter_extensions/filters_form.rb b/lib/active_admin_filter_extensions/filters_form.rb index 8376428..e6390e6 100644 --- a/lib/active_admin_filter_extensions/filters_form.rb +++ b/lib/active_admin_filter_extensions/filters_form.rb @@ -54,7 +54,63 @@ def active_search_sidebar_section # method, so that this gem carries no copy of a method body that belongs to Active Admin. module ViewHelper def active_admin_filters_form_for(search, filters, options = {}) - super(search, filters.transform_values { |opts| FilterOptions.input_options(opts) }, options) + filters = filters.to_h do |attribute, opts| + # Asked of the controller only for a none: filter - the helper exists on resource pages, + # and this method is also mixed into views that are not one. + opts = none_filter_form_options(attribute, opts, search, self) if opts[:none] + [attribute, FilterOptions.input_options(opts)] + end + super(search, filters, options) + end + end + + # Current Filters lists the search's top-level conditions. A None option is a `_null` there, + # reading "is null 1" - and beside other values it is in an OR grouping, which is not listed + # at all. Prepended to ActiveAdmin::Filters::Active, the one class both versions list from. + module CurrentFilters + def initialize(resource, search) + super + labels = search.instance_variable_get(NoneOption::LABELS) + return if labels.blank? + + filters.each { |filter| name_none_filter(filter, labels[filter.condition.key]) } + search.base.groupings.each do |grouping| + null = grouping.conditions.find { |condition| labels.key?(condition.key) } + next unless null + + (grouping.conditions - [null]).each do |condition| + filters << name_none_filter(build_filters([condition]).first, labels[null.key]) + end + end + end + + private + + def name_none_filter(filter, label) + return filter unless label + + filter.extend(NoneActiveFilter).none_label = label + filter + end + end + + # One Current Filters entry of a None option: "Account equals None" for the `_null` alone, + # "Status in None and draft" for the values chosen beside it. + module NoneActiveFilter + attr_writer :none_label + + def values + [@none_label] + (none_alone? ? [] : super.to_a) + end + + def predicate_name + none_alone? ? ::Ransack::Translate.predicate("eq") : super + end + + private + + def none_alone? + condition.predicate.name == "null" end end diff --git a/lib/active_admin_filter_extensions/none_option.rb b/lib/active_admin_filter_extensions/none_option.rb new file mode 100644 index 0000000..e8295bc --- /dev/null +++ b/lib/active_admin_filter_extensions/none_option.rb @@ -0,0 +1,115 @@ +# frozen_string_literal: true + +module ActiveAdminFilterExtensions + # `extensions: { none: true }` - a select filter's option for the records whose attribute is + # empty. The select submits a sentinel under its own key and only the search is handed the + # `_null` it stands for, so defaults, policies and the redirect read the request as submitted. + module NoneOption + # What a select derives. _not_eq and _not_in end the same way, and an OR beside their + # `_not_null` is no reading of "none of these". + KEY = /(? "or", key.to_s => values, null_key => "1" } + end + return searched if groupings.empty? + + existing = searched["g"] + existing = existing.values if existing.is_a?(Hash) + searched.merge("g" => Array(existing) + groupings) + end + + protected + + # What Ransack is handed in place of #filtering_params. + def none_filter_search_params(params) + return params if none_filter_keys.empty? + + NoneOption.search_params(params, none_filter_keys.values, ActiveAdminFilterExtensions.none_value) + end + + # The Current Filters panel is built from the search object alone, so the label of every + # None option this request searched rides on it, under the `_null` key it became. + def label_none_filters(search) + sentinel = ActiveAdminFilterExtensions.none_value unless none_filter_keys.empty? + labels = none_filter_keys.each_with_object({}) do |(attribute, key), result| + next unless Array.wrap(none_filter_request_value(key)).include?(sentinel) + + result[NoneOption.null_key(key)] = none_filter_label(visible_filters[attribute]) + end + search.instance_variable_set(LABELS, labels) if labels.any? + end + + # A none: filter's options with the None option heading its collection. The collection is + # asked of an input built on the form's own search and view, so a Proc, a relation and a + # filter with no collection: resolve the way the form resolves them. + def none_filter_form_options(attribute, options, search, template) + key = none_filter_keys[attribute.to_sym] + return options unless key + + builder = ::ActiveAdmin::Filters::FormBuilder.new(:q, search, template, {}) + collection = build_filter_input(attribute, options, builder).collection + if collection.is_a?(String) + raise ArgumentError, "filter :#{attribute} declares none: but its collection is rendered " \ + "HTML - the None option needs a collection of values to head" + end + + sentinel = ActiveAdminFilterExtensions.none_value + # The collection is pairs by now, and member_label:/member_value: would be sent to them. + options = options.except(:member_label, :member_value) + .merge(collection: [[none_filter_label(options), sentinel]] + collection.to_a) + # Ransack is never handed the sentinel, and the values chosen beside it sit in a grouping, + # so the search object cannot say what is selected - the request can. + requested = none_filter_request_value(key) + Array.wrap(requested).include?(sentinel) ? options.merge(selected: requested) : options + end + + private + + # The search key of every visible none: filter. Materialized on every index request, which + # is also what refuses, loudly, a filter the None option cannot work on. + # + # @return [Hash] filter attribute => search key + def none_filter_keys + @none_filter_keys ||= visible_filters.each_with_object({}) do |(attribute, options), result| + next unless options[:none] + + keys = filter_search_keys(attribute, options) + input = build_filter_input(attribute, options) + unless input.is_a?(::Formtastic::Inputs::SelectInput) && keys.size == 1 && keys.first.match?(KEY) + raise ArgumentError, "filter :#{attribute} declares none: but its #{input.as} input submits " \ + "#{keys.join(' and ')} - the None option needs a select that submits _eq or _in" + end + + result[attribute.to_sym] = keys.first + end + end + + def none_filter_request_value(key) + filtering_params.find { |name, _| name.to_s == key }&.last + end + + def none_filter_label(options) + return options[:none].to_s unless options[:none] == true + + I18n.t(:none, scope: :active_admin_filter_extensions, default: "None") + end + end +end diff --git a/lib/active_admin_filter_extensions/policies.rb b/lib/active_admin_filter_extensions/policies.rb index 0782ece..9fb6082 100644 --- a/lib/active_admin_filter_extensions/policies.rb +++ b/lib/active_admin_filter_extensions/policies.rb @@ -314,10 +314,11 @@ def enforce_scalar_policies(q, attribute, options, keys) end value = value.reject(&:blank?) if value.is_a?(Array) + none = policy_exempt_none_value(attribute, options, key) if (sanitizer = options[:sanitize]) sanitizer = Sanitizers.resolve(sanitizer) - sanitized = sanitize_policed_value(attribute, sanitizer, value) + sanitized = sanitize_policed_value(attribute, sanitizer, value, none) value = sanitized q[key] = value end @@ -328,7 +329,7 @@ def enforce_scalar_policies(q, attribute, options, keys) # Blank input array elements are discarded before searching - ?q[k][]=&q[k][]=draft # is the shape a multi-select submits - so remove them before sanitizing. Sanitized # elements are all judged, including ones the sanitizer emptied. - elements = value.is_a?(Array) ? value : [value] + elements = (value.is_a?(Array) ? value : [value]) - [none] message = elements.lazy .filter_map { |element| ::MethodOrProcHelper.render_in_context(self, validator, element) }.first # nil AND false mean "valid" - `condition && "message"` is how Ruby writes these. @@ -341,6 +342,15 @@ def enforce_scalar_policies(q, attribute, options, keys) end end + # The None option's sentinel is the gem's own, not a value the admin typed, so no value + # policy is handed it - under the none: filter's own key only, where the search rewrites + # it. Anywhere else it is a value like any other, and a way past the policy if exempted. + def policy_exempt_none_value(attribute, options, key) + return unless options[:none] && none_filter_keys[attribute.to_sym] == key.to_s + + ActiveAdminFilterExtensions.none_value + end + # A String, or an Array of Strings - what a multi-valued input submits. def policed_value_shape?(value) value.is_a?(String) || (value.is_a?(Array) && value.all?(String)) @@ -349,8 +359,9 @@ def policed_value_shape?(value) # Element-wise for an Array, so a multi-valued filter is sanitized the way it is # submitted. On dup'd copies: a sanitizer that mutates in place and returns the same # object would otherwise be compared against itself and wave its loop through. - def sanitize_policed_value(attribute, sanitizer, value) - return value.map { |element| sanitize_policed_value(attribute, sanitizer, element) } if value.is_a?(Array) + def sanitize_policed_value(attribute, sanitizer, value, none = nil) + return value.map { |element| sanitize_policed_value(attribute, sanitizer, element, none) } if value.is_a?(Array) + return value if value == none sanitized = ::MethodOrProcHelper.render_in_context(self, sanitizer, value.dup).to_s # The sanitized value lands in the URL and comes back for another pass - a sanitizer diff --git a/lib/active_admin_filter_extensions/search_keys.rb b/lib/active_admin_filter_extensions/search_keys.rb index 0659992..ef537d5 100644 --- a/lib/active_admin_filter_extensions/search_keys.rb +++ b/lib/active_admin_filter_extensions/search_keys.rb @@ -37,8 +37,7 @@ def filter_search_keys(attribute, options) raise_filter_default_error(attribute, "could not work out which search key it submits (#{e.class}: #{e.message}) - name the predicate with a Hash instead") end - def build_filter_input(attribute, options) - builder = filter_input_builder + def build_filter_input(attribute, options, builder = filter_input_builder) options = filter_input_options(options, builder) as = options[:as] || builder.send(:default_input_type, attribute) builder.send(:namespaced_input_class, as) diff --git a/spec/integration/none_option_spec.rb b/spec/integration/none_option_spec.rb new file mode 100644 index 0000000..75e752b --- /dev/null +++ b/spec/integration/none_option_spec.rb @@ -0,0 +1,173 @@ +# frozen_string_literal: true + +require "rails_helper" +require "rack/utils" + +# `none:` gives a select filter an option for the records whose attribute is empty - the one +# question no value of its collection can ask. The select submits a sentinel under its own key, +# and only the search is handed the `_null` condition it stands for. +RSpec.describe "the None option", type: :feature do + let(:none) { ActiveAdminFilterExtensions.none_value } + let(:aa_v4) { ActiveAdminFilterExtensions.aa_v4? } + let!(:acme) { Account.create!(name: "Acme") } + let!(:zenith) { Account.create!(name: "Zenith") } + + before do + Post.create!(title: "acme post", status: "published", position: 20, account: acme) + Post.create!(title: "zenith post", status: "draft", position: 1, account: zenith) + Post.create!(title: "orphan post") + end + + def query_of(url) + Rack::Utils.parse_nested_query(URI.parse(url).query.to_s) + end + + def options_of(name) + page.all("select[name='#{name}'] option").map { |option| [option.text, option.value] } + end + + # The entry of one search key in the Current Filters panel, which both moved and changed its + # hook in Active Admin 4. + def current_filter(key) + if aa_v4 + "#active_search_sidebar_section li[data-filter='#{key}']" + else + "#search_status_sidebar_section li.current_filter_#{key}" + end + end + + it "renders first, after the blank option" do + visit "/admin/none_posts" + + expect(options_of("q[account_id_eq]")) + .to eq([["Any", ""], ["None", none], ["Acme", acme.id.to_s], ["Zenith", zenith.id.to_s]]) + end + + it "heads a multiple select, under the label the filter gave it" do + visit "/admin/none_posts" + + expect(options_of("q[status_in][]")) + .to eq([["No status", none], %w[draft draft], %w[published published]]) + end + + it "lists only the records with the attribute empty" do + visit "/admin/none_posts" + select "None", from: "q[account_id_eq]" + click_button "Filter" + + expect(page).to have_content("orphan post") + expect(page).to have_no_content("acme post") + expect(page).to have_no_content("zenith post") + end + + it "stays selected after the submit, under the key the select submitted" do + # Ransack is handed account_id_null, so neither the search object nor a rewritten URL could + # say which option was picked - the request, left as submitted, does. + visit "/admin/none_posts" + select "None", from: "q[account_id_eq]" + click_button "Filter" + + expect(query_of(page.current_url)["q"]).to include("account_id_eq" => none) + expect(page).to have_select("q[account_id_eq]", selected: "None") + end + + it "returns the union for None beside a value on a multiple select" do + visit "/admin/none_posts" + select "No status", from: "q[status_in][]" + select "draft", from: "q[status_in][]" + click_button "Filter" + + expect(page).to have_content("orphan post") + expect(page).to have_content("zenith post") + expect(page).to have_no_content("acme post") + expect(page).to have_select("q[status_in][]", selected: ["No status", "draft"]) + end + + it "searches None alone on a multiple select" do + visit "/admin/none_posts?q%5Bstatus_in%5D%5B%5D=#{none}" + + expect(page).to have_content("orphan post") + expect(page).to have_no_content("zenith post") + expect(page).to have_select("q[status_in][]", selected: ["No status"]) + end + + it "filters the formats the redirect never touches" do + visit "/admin/none_posts.csv?q%5Baccount_id_eq%5D=#{none}" + + expect(page).to have_content("orphan post") + expect(page).to have_no_content("acme post") + end + + it "raises for a filter that is not a select" do + expect { visit "/admin/banana_none_posts" } + .to raise_error(ArgumentError, /:title_cont declares none:.*needs a select that submits _eq or _in/m) + end + + it "answers a required: filter" do + # Left unanswered, the filter imposes its default beside the title... + visit "/admin/required_none_posts?q%5Btitle_cont%5D=post" + + expect(query_of(page.current_url)["q"]) + .to eq("title_cont" => "post", "account_id_eq" => acme.id.to_s) + + # ...and "without an account" is an answer, not an absence to fill in. + visit "/admin/required_none_posts?q%5Btitle_cont%5D=post&q%5Baccount_id_eq%5D=#{none}" + + expect(query_of(page.current_url)["q"]).to eq("title_cont" => "post", "account_id_eq" => none) + expect(page).to have_content("orphan post") + expect(page).to have_no_content("acme post") + end + + it "can be the filter's default" do + visit "/admin/default_none_posts" + + expect(query_of(page.current_url)["q"]).to eq("account_id_eq" => none) + expect(page).to have_content("orphan post") + expect(page).to have_no_content("acme post") + expect(page).to have_select("q[account_id_eq]", selected: "None") + end + + describe "beside value policies" do + it "is not handed to validate:" do + # :integer would refuse the sentinel and reset the filter to the whole table. + visit "/admin/policed_none_posts?q%5Baccount_id_eq%5D=#{none}" + + expect(page).to have_no_content("Account filter has an invalid value.") + expect(page).to have_content("orphan post") + expect(page).to have_no_content("acme post") + end + + it "is not handed to sanitize:, while the values beside it are" do + # :digits would empty the sentinel; the URL keeps it and carries the cleaned value. + visit "/admin/policed_none_posts?q%5Bposition_in%5D%5B%5D=#{none}&q%5Bposition_in%5D%5B%5D=2x0" + + expect(query_of(page.current_url)["q"]).to eq("position_in" => [none, "20"]) + expect(page).to have_content("orphan post") + expect(page).to have_content("acme post") + expect(page).to have_no_content("zenith post") + end + + it "leaves every other value to the policy" do + visit "/admin/policed_none_posts?q%5Baccount_id_eq%5D=abc" + + expect(page).to have_content("Account filter has an invalid value.") + end + end + + describe "in the Current Filters panel" do + it "reads as the option, not as the condition it became" do + # Left to Active Admin the `_null` condition reads "Account is null 1". + visit "/admin/none_posts?q%5Baccount_id_eq%5D=#{none}" + + expect(page).to have_css(current_filter("account_id_null"), text: /Account equals\s*None/) + end + + it "lists None beside the values chosen with it" do + # Those sit in an OR grouping, which the panel does not list: left to Active Admin it + # says nothing is filtered. + visit "/admin/none_posts?q%5Bstatus_in%5D%5B%5D=#{none}&q%5Bstatus_in%5D%5B%5D=draft" + + expect(page).to have_css(current_filter("status_in"), text: /Status in\s*No status and draft/) + end + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index b5452ad..7f3eb0c 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -11,6 +11,7 @@ require "active_admin_filter_extensions/search_keys" require "active_admin_filter_extensions/required_filters" require "active_admin_filter_extensions/filter_defaults" +require "active_admin_filter_extensions/none_option" require "active_admin_filter_extensions/policies" # `DataAccess` only needs `params`, `active_admin_config` and something that answers `ransack`. @@ -64,6 +65,7 @@ def filter_ransack_options = {} include ActiveAdminFilterExtensions::SearchKeys include ActiveAdminFilterExtensions::RequiredFilters include ActiveAdminFilterExtensions::FilterDefaults + include ActiveAdminFilterExtensions::NoneOption end RSpec.configure do |config| diff --git a/spec/support/rails_template.rb b/spec/support/rails_template.rb index c14552c..f094593 100644 --- a/spec/support/rails_template.rb +++ b/spec/support/rails_template.rb @@ -7,13 +7,17 @@ File.write("app/assets/config/manifest.js", "//= link_tree ../images\n") # One column per filter input type, so every input can be exercised against a real index. +# account_id is a plain nullable column rather than a reference: a post without an account is +# what the None option filters for. generate :model, "post title:string body:text status:string position:integer " \ - "published_date:date starred:boolean --force" + "published_date:date starred:boolean account_id:integer --force" +generate :model, "account name:string --force" inject_into_file "app/models/post.rb", + " belongs_to :account, optional: true\n" \ " def self.ransackable_attributes(auth_object = nil)\n" \ - " %w[id title body status position published_date starred]\n" \ + " %w[id title body status position published_date starred account_id]\n" \ " end\n" \ " def self.ransackable_associations(auth_object = nil)\n" \ " []\n" \ @@ -620,6 +624,42 @@ def filter_defaults_apply? filter :title end + ActiveAdmin.register Post, as: "NonePost" do + # The None option on a single and on a multiple select: a relation behind a Proc with the + # shipped label, an Array with the filter's own. + filter :account, as: :select, collection: proc { Account.order(:name) }, extensions: { none: true } + filter :status, as: :select, multiple: true, collection: %w[draft published], + extensions: { none: "No status" } + end + + ActiveAdmin.register Post, as: "BananaNonePost" do + # A :string filter has no option to add - the suite proves that raises. + filter :title_cont, as: :string, extensions: { none: true } + end + + ActiveAdmin.register Post, as: "RequiredNonePost" do + # "Without an account" is an answer to a required filter, not its absence. + filter :title_cont, as: :string + filter :account, as: :select, collection: proc { Account.order(:name) }, + extensions: { none: true, required: true, + default: -> { Account.find_by(name: "Acme")&.id } } + end + + ActiveAdmin.register Post, as: "DefaultNonePost" do + # The sentinel as the default: the index opens on the posts without an account. + filter :account, as: :select, collection: proc { Account.order(:name) }, + extensions: { none: true, default: -> { ActiveAdminFilterExtensions.none_value } } + end + + ActiveAdmin.register Post, as: "PolicedNonePost" do + # Value policies beside the None option: the sentinel is not a value the admin typed, so + # neither policy is handed it - :digits would empty it, :integer would refuse it. + filter :account, as: :select, collection: proc { Account.order(:name) }, + extensions: { none: true, validate: :integer } + filter :position, as: :select, multiple: true, collection: [1, 20], + extensions: { none: true, sanitize: :digits, validate: :integer } + end + ActiveAdmin.register Post, as: "CollidingNoticePost" do # The notice on its DEFAULT flash key - the same :notice a batch action writes. Both have # to coexist on the redirect: the arriving message wins, it names what just happened. From c2dcd942d74eb2d6c819013cbce318ed53bb3480 Mon Sep 17 00:00:00 2001 From: Denis Talakevich Date: Sat, 28 Nov 2026 19:19:32 +0200 Subject: [PATCH 2/5] Add a Present option, option classes and predicate choices Co-Authored-By: Clanker --- README.md | 128 +++++++-- .../active_admin_filter_extensions.js | 66 +++++ config/importmap.rb | 4 + config/locales/en.yml | 4 +- lib/active_admin_filter_extensions.rb | 21 +- .../data_access.rb | 8 +- lib/active_admin_filter_extensions/engine.rb | 24 ++ .../filter_defaults.rb | 12 +- .../filter_options.rb | 2 +- .../filters_form.rb | 66 +++-- .../marker_options.rb | 240 +++++++++++++++++ .../none_option.rb | 115 -------- .../policies.rb | 26 +- spec/integration/predicate_option_spec.rb | 248 ++++++++++++++++++ spec/integration/present_option_spec.rb | 210 +++++++++++++++ spec/marker_options_spec.rb | 48 ++++ spec/spec_helper.rb | 4 +- spec/support/rails_template.rb | 67 ++++- 18 files changed, 1101 insertions(+), 192 deletions(-) create mode 100644 app/assets/javascripts/active_admin_filter_extensions.js create mode 100644 config/importmap.rb create mode 100644 lib/active_admin_filter_extensions/engine.rb create mode 100644 lib/active_admin_filter_extensions/marker_options.rb delete mode 100644 lib/active_admin_filter_extensions/none_option.rb create mode 100644 spec/integration/predicate_option_spec.rb create mode 100644 spec/integration/present_option_spec.rb create mode 100644 spec/marker_options_spec.rb diff --git a/README.md b/README.md index ea583e5..eccbbe2 100644 --- a/README.md +++ b/README.md @@ -28,8 +28,9 @@ filter :created_at, as: :date_time_range, floors on two-ended filters. * [`message:`](#value-policies-sanitize-and-validate) and plain-i18n defaults for every violation text. -* [`none:`](#none-option) - a None option on a select filter, for the records whose attribute - is empty. +* [`none:` / `present:`](#none-and-present-options) - None and Present options on a select + filter, and None and Present predicates on a string or numeric one, for the records whose + attribute is empty and the ones where it is not. * [`default_filters_notice`](#telling-the-admin-why) - the flash that tells the admin why the page shows a slice; [`require_any_filter`](#resource-level-guard) - an index that waits to be asked. @@ -338,38 +339,126 @@ lands in `flash[:error]` (and rides the redirect), and the filter's declared `de any - refills through the ordinary merge. The defaults notice stays quiet on that render: the error already explains why the page shows the default slice. -## None option +## None and Present options -A select filter cannot ask for the records whose attribute is empty: no value of its collection -means that. `none:` adds the option, first in the list after the blank one: +A select filter cannot ask for the records whose attribute is empty, or for the ones where it +holds anything at all: no value of its collection means either. `none:` and `present:` add the +options, first in the list after the blank one, None before Present: ```ruby -filter :account, as: :select, collection: proc { Account.order(:name) }, extensions: { none: true } +filter :account, as: :select, collection: proc { Account.order(:name) }, + extensions: { none: true, present: true } filter :status, as: :select, multiple: true, collection: %w[draft published], extensions: { none: "No status" } # the option's label ``` -`true` labels the option from the i18n key `active_admin_filter_extensions.none` ("None"); a -String is the label itself. Picking it searches `_null` on the filter's attribute. On a multiple -select, None beside other values searches "any of these, or empty". +`true` labels the option from the i18n keys `active_admin_filter_extensions.none` ("None") and +`active_admin_filter_extensions.present` ("Present"); a String is the label itself. None +searches `_null` on the filter's attribute, Present searches `_not_null`. On a multiple select: -The select submits a sentinel under its own key - `q[account_id_eq]=__none__` - and only the -search is handed the `_null` condition. The URL, the form and the other extensions read the -request as submitted: `required:` counts None as an answer, `sanitize:` and `validate:` are not -handed the sentinel, and `default: -> { ActiveAdminFilterExtensions.none_value }` opens the -index on the empty records. The Current Filters panel shows the label: "Account equals None". -Move the sentinel where a real value could spell the same thing: +* None beside other values searches "any of these, or empty". +* Present beside other values searches Present alone: every value is a present one. +* None and Present together search every record, so no condition is applied. + +The select submits a marker under its own key - `q[account_id_eq]=__none__` or +`q[account_id_eq]=__present__` - and only the search is handed the condition. The URL, the form +and the other extensions read the request as submitted: `required:` counts either option as an +answer, `sanitize:` and `validate:` are not handed the marker, and +`default: -> { ActiveAdminFilterExtensions.none_value }` opens the index on the empty records. +The Current Filters panel shows the label: "Account equals None", "Account equals Present". +Move a marker where a real value could spell the same thing: ```ruby ActiveAdminFilterExtensions.none_value = "__empty__" +ActiveAdminFilterExtensions.present_value = "__filled__" +``` + +### On a string or numeric filter + +A `:string` or `:numeric` filter that picks its predicate from a dropdown takes the same two +options, as two more predicates closing the list: + +```ruby +filter :title, extensions: { none: true, present: true } +filter :position, as: :numeric, extensions: { none: "No position" } +``` + +A string filter searches `_blank` and `_present`, so an empty string counts as none; a numeric +one searches `_null` and `_not_null`. These are Ransack's own predicates and the URL says them +as they are searched: `q[title_blank]=1`. `required:` counts them as an answer, `sanitize:` and +`validate:` are not handed the `1`, and the Current Filters panel reads "Title equals None". + +Such a predicate has nothing to type, and Active Admin leaves an empty box out of the submit. +The gem's script fills the box and hides it. Without the script the two predicates filter +nothing, so load it on every page with a filters form. + +Active Admin 3 (Sprockets), in `app/assets/javascripts/active_admin.js`: + +```javascript +//= require active_admin_filter_extensions +``` + +Active Admin 4 (import map): the gem pins the module `active_admin_filter_extensions` into +`ActiveAdmin.importmap`. If your Active Admin has the `javascript_modules` setting, the gem adds +itself to it and pages import it automatically. Otherwise override +`app/views/active_admin/_html_head.html.erb` (copy it from Active Admin) and add after the +`javascript_importmap_tags` line: + +```erb +<%= javascript_import_module_tag "active_admin_filter_extensions" %> +``` + +If you use active_admin_theme 4, add the module to its list in an initializer instead: + +```ruby +ActiveAdminTheme.javascripts += %w[active_admin_filter_extensions] ``` -Only a select that submits `_eq` or `_in` takes the option; `none:` on any other filter raises. +The script listens on `document`, so it does not depend on the order it is loaded in. For a +filters form the page inserts on its own, call `ActiveAdminFilterExtensions.sync(form)`. + +Any other filter raises on `none:` or `present:`: check boxes, a date range, a select that +submits `_not_eq` or `_not_in`, a string filter named after its predicate (`filter :title_cont`). + +### Styling the options + +The gem ships no CSS. Every option it adds, to a select or to a predicate dropdown, carries +classes and a data attribute to style: + +```html + + +``` + +A Hash gives the option classes of its own beside the label, appended to the gem's: + +```ruby +filter :account, as: :select, + extensions: { none: { label: "No account", class: "text-red-700 italic" }, + present: { class: "font-bold" } } +``` + +```css +.filter-extensions-none { font-style: italic; } +[data-filter-extensions-option] { color: #b91c1c; } +``` + +A browser styles an `