使用 Filterific gem 按 Rails 中的属性过滤
Filter by attribute in Rails by using Filterific gem
我的用户模型具有 role
(字符串)属性。我想通过此角色属性过滤我的用户。
我使用 filterific gem 进行过滤。
这是我的 index
操作:
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
其中 options_for_select
方法定义:
# user.rb
def self.options_for_select
order('LOWER(role)').map { |e| [e.role, e.id] }
end
在我看来:
<%= f.select(
:with_role,
@filterrific.select_options[:with_role],
{ include_blank: '- Any -' }
) %>
我在 user.rb:
中有一个范围
scope :with_role, lambda { |roles|
where(role: [*roles])
}
我只有五个角色,但在我的select中每个角色都出现了很多次,所以我不知道如何return在options_for_select
方法中独特的角色。
其次,options_for_select
return用户的 ID 作为每个选项标签中的值,但我希望它 return 角色本身。
您在 User
模型上定义 options_for_select
。因此它会提取数据库中的每个用户记录及其关联的角色条目以及用户 ID。
在控制器中尝试以下而不是 User.options_for_select
:
select_options: {
with_role: ['Role1', 'Role2', 'Role3']
},
我的用户模型具有 role
(字符串)属性。我想通过此角色属性过滤我的用户。
我使用 filterific gem 进行过滤。
这是我的 index
操作:
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
其中 options_for_select
方法定义:
# user.rb
def self.options_for_select
order('LOWER(role)').map { |e| [e.role, e.id] }
end
在我看来:
<%= f.select(
:with_role,
@filterrific.select_options[:with_role],
{ include_blank: '- Any -' }
) %>
我在 user.rb:
中有一个范围scope :with_role, lambda { |roles|
where(role: [*roles])
}
我只有五个角色,但在我的select中每个角色都出现了很多次,所以我不知道如何return在options_for_select
方法中独特的角色。
其次,options_for_select
return用户的 ID 作为每个选项标签中的值,但我希望它 return 角色本身。
您在 User
模型上定义 options_for_select
。因此它会提取数据库中的每个用户记录及其关联的角色条目以及用户 ID。
在控制器中尝试以下而不是 User.options_for_select
:
select_options: {
with_role: ['Role1', 'Role2', 'Role3']
},