0.01
Low commit activity in last 3 years
No release in over a year
Enable enum values in Ransack search
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies
 Project Readme

RansackEnum

Enable enum values in Ransack search.

Installation

Add this line to your application's Gemfile:

gem 'ransack', '~> 2.0'
gem 'ransack-enum', '~> 1.0'

And then execute:

$ bundle install

Usage

When enum is defined in ActiveRecord, the search method of ransack is redefined. There is no need to add any special code.

class Post < ActiveRecord::Base
  enum status: { unpublished: 0, published: 1 }

  # after ActiveRecord 7, the following is also possible.
  # enum :status, { unpublished: 0, published: 1 }
end

Search by enum value.

Post.ransack(status_eq: 'published').result.to_sql
# SELECT "posts".* FROM "posts" WHERE "posts"."status" = 1
Post.ransack(status_in: %w[unpublished published]).result.to_sql
# SELECT "posts".* FROM "posts" WHERE "posts"."status" IN (0, 1)

Search with actual values as before.

Post.ransack(status_eq: 1).result.to_sql
# SELECT "posts".* FROM "posts" WHERE "posts"."status" = 1
Post.ransack(status_in: [0, 1]).result.to_sql
# SELECT "posts".* FROM "posts" WHERE "posts"."status" IN (0, 1)

Configuration

Enable / Disable enum value search in the configuration. Default is enabled.

# config/initializers/ransack.rb

Ransack.configure do |config|
  # ...
end

RansackEnum.configure do |config|
  # enabled (default)
  config.enabled = true

  # disabled
  # config.enabled = false
end

Feature

  • Enable to convert enum i18n value to search value

Development

After checking out the repo, run bin/setup to install dependencies. Then, run bundle exec rake to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/shoma07/ransack-enum.

License

The gem is available as open source under the terms of the MIT License.