Rails Ransack - 如何搜索多个值

时间:2013-11-07 07:03:03

标签: ruby-on-rails ruby-on-rails-3.2 ransack

使用Ransack gem我可以使用复选框为某些值实现搜索。但是,这不适用于多个复选框。我错过了什么?

查看:

<%= search_form_for @search do |f| %>
  Part Time:<%= check_box_tag "q[job_type_cont]", value = "Part time" %></br>
  Full Time:<%= check_box_tag "q[job_type_cont]", value = "Full time" %></br>
  <%= f.submit "Search" %>
<% end %>

指数行动:

def index
  @search = Job.search(params[:q])
  @jobs = @search.result
 end

2 个答案:

答案 0 :(得分:2)

您的观点始终只会在参数[:q] [:job_type_cont] 中发送一个值 它将是兼职全职的字符串 要接收多个值,您需要将其更改为数组(需要更改复选框名称属性),如下所示

Part Time: <%= check_box_tag "q[job_type_cont][]", "Part time" %></br>
Full Time: <%= check_box_tag "q[job_type_cont][]", "Full time" %>

通过上述实现,在控制器中 params [:q] [:job_type_cont] 将是一个包含视图中选定值的数组

答案 1 :(得分:2)

Kalpesh建议

Part Time: <%= check_box_tag "q[job_type_cont][]", "Part time" %></br>
Full Time: <%= check_box_tag "q[job_type_cont][]", "Full time" %>

@search = Job.search(job_type_in: params[:q][:job_type_cont])
@jobs = @ search.result

这真是一种迂回的说法:

Part Time: <%= check_box_tag "q[job_type_in][]", "Part time" %></br>
Full Time: <%= check_box_tag "q[job_type_in][]", "Full time" %>

这样你的控制器就不需要有趣的业务了:

@search = Job.search(params[:q])