Ransack Configuration Options: A Complete Guide to `strip_whitespace`, `ignore_unknown_conditions`, and More
Ransack provides global configuration options in Ransack::Configuration that let you customize search parameter handling, whitespace stripping, error behavior for unknown conditions, and UI elements like sort arrows.
The activerecord-hackery/ransack gem exposes a centralized configuration system defined in lib/ransack/configuration.rb. These settings control everything from how search parameters are parsed to how PostgreSQL sorts null values. Understanding these Ransack configuration options allows you to tailor the search behavior to your Rails application's specific requirements.
Core Ransack Configuration Options
The Ransack::Configuration module stores defaults in an options hash initialized when the gem loads. You can override these in a Rails initializer using the Ransack.configure DSL.
search_key
The search_key option defines the query parameter name Ransack looks for in params. By default, it is set to :q, meaning Ransack expects params[:q].
Changing this is useful when you need multiple independent search forms on the same page. For example, setting config.search_key = :product_query would require you to pass params[:product_query] to your search object.
strip_whitespace
By default, strip_whitespace is set to true. When enabled, Ransack automatically removes leading and trailing whitespace from string search values before building the query.
This prevents accidental mismatches when users copy-paste values with extra spaces. However, if your application requires exact whitespace matching (for example, searching formatted codes where spaces are significant), disable this in your initializer:
Ransack.configure do |config|
config.strip_whitespace = false
end
The accessor is defined at lines 96-98 in lib/ransack/configuration.rb.
ignore_unknown_conditions
The ignore_unknown_conditions option controls error handling when Ransack encounters unrecognized predicates, attributes, or conditions. It defaults to true, meaning Ransack silently discards unknown conditions.
Setting this to false causes Ransack to raise an exception, which is invaluable during development for catching typos in predicate names (like writing name_contain instead of name_cont):
Ransack.configure do |config|
config.ignore_unknown_conditions = false
end
This option is defined at line 31, with the accessor at lines 100-102.
hide_sort_order_indicators and Custom Arrows
The hide_sort_order_indicators option (default false) controls whether up/down arrow icons render next to sortable column headers in view helpers.
You can also customize the arrow markup using custom_arrows. By default, Ransack uses HTML entities (▼ for down, ▲ for up). You can replace these with icon fonts:
Ransack.configure do |config|
config.hide_sort_order_indicators = false
config.custom_arrows = {
up_arrow: '<i class="fa fa-arrow-up"></i>',
down_arrow: '<i class="fa fa-arrow-down"></i>',
default_arrow: '<i class="fa fa-arrow-right"></i>'
}
end
These are defined at lines 32-35 and 137-141, 183-185.
postgres_fields_sort_option
For PostgreSQL users, postgres_fields_sort_option allows you to specify NULLS FIRST or NULLS LAST behavior when sorting. It accepts :nulls_first or :nulls_last, defaulting to nil (database default).
Ransack.configure do |config|
config.postgres_fields_sort_option = :nulls_last
end
This is defined at line 37 with the accessor at lines 160-172, and is utilized in lib/ransack/adapters/active_record/base.rb.
sanitize_scope_args
The sanitize_scope_args option (default true) determines whether custom scope arguments are coerced to booleans. When enabled, string values like 'true' and 'false' are converted to actual boolean types.
Disable this if you need to preserve the original string values:
Ransack.configure do |config|
config.sanitize_custom_scope_booleans = false
end
Note that the accessor method is named sanitize_custom_scope_booleans= (lines 55-57), while the option key is sanitize_scope_args (line 36).
default_predicate
When ignore_unknown_conditions is true and an unknown predicate is supplied, Ransack can fall back to a default_predicate (commonly 'eq' for equality). This is accessed via default_predicate= at lines 113-115.
Ransack.configure do |config|
config.default_predicate = 'eq'
config.ignore_unknown_conditions = true
end
How to Configure Ransack in Your Rails Application
All configuration happens through an initializer. Create config/initializers/ransack.rb and use the block DSL:
# config/initializers/ransack.rb
Ransack.configure do |config|
# Strict mode: raise on typos
config.ignore_unknown_conditions = false
# Keep whitespace for exact matching
config.strip_whitespace = false
# Use custom search param
config.search_key = :filter
# PostgreSQL null handling
config.postgres_fields_sort_option = :nulls_last
# Custom sort icons
config.custom_arrows = {
up_arrow: '▲',
down_arrow: '▼',
default_arrow: '◆'
}
end
Changes take effect immediately after server restart.
Where Configuration Options Are Used in the Source Code
Understanding how these options flow through the codebase helps debug unexpected behavior:
-
lib/ransack/configuration.rb– Defines theoptionshash (lines 30-38) and all accessor methods. This is the source of truth for defaults. -
lib/ransack/search.rb– Consumesstrip_whitespacewhen normalizing string inputs andignore_unknown_conditionswhen validating predicates. It also readssearch_keyto know which params hash to process. -
lib/ransack/helpers/form_helper.rb– Usessearch_keyto generate form field names and URLs. -
lib/ransack/helpers.rb– Sort-link helpers checkhide_sort_order_indicatorsand the arrow configuration options to render the correct HTML. -
lib/ransack/adapters/active_record/base.rb– Appliespostgres_fields_sort_optionwhen constructingORDER BYclauses for PostgreSQL databases.
Summary
- Ransack configuration options are centralized in
Ransack::Configurationand overridden viaRansack.configurein an initializer. strip_whitespace(defaulttrue) automatically trims string search values to prevent accidental mismatches.ignore_unknown_conditions(defaulttrue) silently drops invalid predicates; set tofalseto raise exceptions and catch typos.search_keycontrols the query parameter name (default:q), enabling multiple searches per page.- PostgreSQL-specific options like
postgres_fields_sort_optionallow fine-tuning of null value ordering. - View helpers respect
hide_sort_order_indicatorsandcustom_arrowsfor sortable table headers.
Frequently Asked Questions
What happens if I set ignore_unknown_conditions to false?
When ignore_unknown_conditions is set to false, Ransack will raise a Ransack::UnknownConditionError (or similar exception) whenever it encounters a predicate, attribute, or condition it does not recognize. This is useful during development to catch typos in search forms, but should be used cautiously in production if you rely on dynamic search fields.
Does strip_whitespace affect all search fields or just text inputs?
The strip_whitespace option applies to string values within the search parameters before Ransack builds the query. It affects any string-based predicate values (like name_cont or email_eq) regardless of the HTML input type, but does not modify non-string values such as integers, dates, or booleans.
How do I use multiple independent search forms on the same page?
To support multiple search forms, change the search_key configuration option for each distinct search context. For example, set config.search_key = :product_search for a product filter and keep the default :q for a user search. In your controller, instantiate each search using the appropriate key from params, such as Product.ransack(params[:product_search]) and User.ransack(params[:q]).
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →