Rails过滤索引与复选框

时间:2015-09-09 03:43:18

标签: ruby-on-rails

我觉得我应该这样说,我已经知道关于这个话题已经有几十个问题了,但是我花了几个小时阅读这些问题所有这些都没有找到一个简单,直截了当的概述这样做的方式。为什么这看起来像这么困难的操作?真的没有简化的方法吗?

我有一个Employee模型,其中包含一个字符串“location”。在索引视图中,我想过滤允许用户单击复选框以过滤显示的员工。我设法将某些东西放在一起,但是当我点击提交按钮时,它会尝试使用show route,而不是重新显示索引。

这是索引...

index.html.erb

<% provide(:title, 'All employees') %>
<h1>All Employees</h1>

<!-- create check boxes for filterining -->
<%= form_tag url: employees_path, :method => :get do %>
    <%= label_tag "NYC" %>  <%= check_box_tag 'location[]', "NYC", checked: true %>
    <%= check_box_tag 'location[]', "Paris" %>
    <%= check_box_tag 'location[]', "Rome" %>
    <%= submit_tag 'Submit' %>
<% end %>


<table>
  <tr>
    <th scope="col">Name</th>
    <th scope="col">Location</th>
  </tr>
  <% @employees.each do |employee| %>
  <tr>
    <td><%= link_to employee.name, employee %></td>
    <td><%= employee.location %></td>
  </tr>
  <% end %>
</table>

控制器......

class EmployeesController < ApplicationController

  def index
    #@employees = Employee.all
    @employees = Employee.where("location IN (?)", params[:location])
  end

  def show
    @employee = Employee.find(params[:id])
  end
end

这是日志....

Started GET "/employees" for 64.134.36.1 at 2015-09-09 03:59:08 +0000
  [1m[36mActiveRecord::SchemaMigration Load (0.2ms)[0m  [1mSELECT "schema_migrations".* FROM "schema_migrations"[0m
Processing by EmployeesController#index as HTML
  [1m[35mEmployee Load (0.3ms)[0m  SELECT "employees".* FROM "employees" WHERE (location IN (NULL))
  Rendered employees/index.html.erb within layouts/application (4.7ms)
Completed 200 OK in 285ms (Views: 268.9ms | ActiveRecord: 0.4ms)


Started POST "/employees?method=get&url=%2Femployees" for 64.134.36.1 at 2015-09-09 03:59:12 +0000
Processing by EmployeesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"ewCa8gn7P5X8SstapIWMacMj2qqw4SLWw9lrCqLt0HHeiNKqvSftDvCEC7AJo9NdZh0N2hyzifZoPRDgXzkm5w==", "location"=>["NYC"], "commit"=>"Submit", "method"=>"get", "url"=>"/employees"}
  Rendered employees/create.html.erb within layouts/application (0.3ms)
Completed 200 OK in 81ms (Views: 79.6ms | ActiveRecord: 0.0ms)

2 个答案:

答案 0 :(得分:0)

from_tag进行幻灯片更改,如下所示,ruby代码将无法在""评估

 <%= form_tag url: employees_path, :method => :get do %>
  #your codes goes here 

或者

 <%= form_tag employees_path, :method => :get do %>
  #your codes goes here 

或者

 <%= form_tag '/employees', :method => :get do %>
  #your codes goes here 

答案 1 :(得分:0)

我希望它能解决问题,

<form action='<%= employees_path %>' method='get' >
  # other codes 
</form>