How to add scope for multiple enums in rails
I have a selection that displays all the enums of an object:
<%= f.select( :state_user
, User.states.keys.map {|state| [state.titleize,state] }) %>
How can I create a region that allows me to select multiple states?
For example, I want to filter out all users who are either inactive or suspended.
thank
source to share
Not sure if you're still looking for something like this, but here's what I found.
Decision
I was able to implement this using the following
scope :for_states, -> (*state_names) {
where(state: states.values_at(*Array(state_names).flatten))
}
The argument *state_names
allows any number of arguments to be packed into an array state_names
. Array(state_names)
ensures that this, if one argument was passed, will be treated as an array. Finally, flatten
it allows you to pass one array as an argument. After that splat ( *
) unpacks all the elements of this array as method arguments values_at
.
You can use it like this:
-
User.for_states :one_state
-
User.for_states :state_1, :state_2
-
User.for_states [:state_1, :state_2]
If you don't need a way to keep it that flexible, it could be simplified.
Future
According to the Edge Rails Docs, this should be even easier in Rails 5 and you should just be able to do
User.where(state: [:state_1, :state_2])
source to share