基于Ruby中的多个选择进行过滤

时间:2018-06-12 04:57:50

标签: ruby-on-rails ruby

如何使用多个选择过滤我的用户表?我尝试将其更改为单选,过滤器正常运行,并且正确执行sql但我想将其更改为多选。我试过了,过滤器无法正常工作。我怎么能完成它?
我的形式是:

<%= f.label :department_id %><br>
<%= f.select :department_id, Department.all.map { |d| [d.name, d.id] }, {include_blank: true}, multiple: true %>

提交表单后,它会在其模型中执行一个函数。这是使单个选择工作的一段代码,但它不能在多个选择中工作:users = User.where(["users.department_id = ?", department_id]) if department_id.present?。如何让它适用于多种选择?

编辑:我注意到它在多次选择时没有返回任何内容。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

即使是多次选择也会采用类似的方法。

假设您想要使用部门和位置进行过滤:

<%= f.label :department_id %><br>
<%= f.select :department_id, Department.all.map { |d| [d.name, d.id] }, {include_blank: true}, multiple: true %>
<%= f.label :location_id %><br>
<%= f.select :location_id, Location.all.map { |d| [d.name, d.id] }, {include_blank: true}, multiple: true %>

更改模型中的功能以包含以下内容:

@users = User.where(["department_id = ?", department_id]) if department_id.present?
@users = @users.where(["location_id = ?", location_id]) if location_id.present?

在上面,使用部门的第一行过滤器。在第二行中,它会使用位置过滤已过滤的用户。