arrow_backward Back to blog

Easily Search on ActiveRecord Attributes

Rails’s named_scopes are great, and the ability to chain named_scopes together are even better. I am sure many of us have done something like this before:

That would give you the active users who live in the state of Virginia. You would define something like these in your User model:

One recent client project has a model where the database table has 30-something columns. Doing these named_scopes became tedious and repetitive. That makes it not fun anymore.

So Dave Pranata and I wrote the searchable_attributes Rails plugin so we could stop worrying about explicitly defining these named_scopes once and for all.

To use it, you just install it like any other Rails plugin:

The plugin will automatically define a bunch of named_scopes for you if you include this in your model:

You can then search on your models with something like this:

Take a look in the plugin’s lib/searchable_attributes.rb for a list of automatically defined named_scopes.

arrow_backBack

New Project Request