【问题标题】:Filter by attribute in Rails by using Filterific gem使用 Filterific gem 在 Rails 中按属性过滤
【发布时间】:2015-07-07 06:35:40
【问题描述】:

我有具有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])
      }

我只有五个角色,但是在我的选择中每个角色出现了很多次,所以我不知道如何在options_for_select 方法中返回唯一角色。

其次,options_for_select 在每个选项标签中返回用户 ID 作为值,但我希望它返回角色本身。

【问题讨论】:

    标签: ruby-on-rails filterrific


    【解决方案1】:

    您在 User 模型上定义 options_for_select。因此,它会提取数据库中的每个用户记录及其关联的角色条目,以及用户 ID。

    在控制器中尝试以下操作,而不是 User.options_for_select

    select_options: {
      with_role: ['Role1', 'Role2', 'Role3']
    },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-05
      • 1970-01-01
      • 1970-01-01
      • 2020-08-03
      相关资源
      最近更新 更多