I have User model which has role
(String) attribute. I want to filter my Users by this role attribute.
For filtering I'm using filterific gem.
Here is my index
action:
def index
@filterrific = initialize_filterrific(
User,
params[:filterrific],
select_options: {
with_role: User.options_for_select
},
) or return
@users = @filterrific.find.page(params[:page])
end
where options_for_select
method is defined:
# user.rb
def self.options_for_select
order('LOWER(role)').map { |e| [e.role, e.id] }
end
and in my view:
<%= f.select(
:with_role,
@filterrific.select_options[:with_role],
{ include_blank: '- Any -' }
) %>
and I have a scope in my user.rb:
scope :with_role, lambda { |roles|
where(role: [*roles])
}
I have only five roles, but in my select each role appears many times, so I don't know how to return unique roles in options_for_select
method.
Secondly, options_for_select
returns id's of user as a value in each option tag, but I want it to return role itself.
You define options_for_select
on the User
model. So it pulls in every user record in your database and its associated role entry, along with the user id.
Try the following instead of User.options_for_select
in the controller:
select_options: {
with_role: ['Role1', 'Role2', 'Role3']
},