rails collection_select 参数

rails collection_select params

所以我试图根据 collection_select 下拉框过滤一些数据。

我可以成功地使用 text_field_tag 来过滤数据,所以我假设我的过滤器工作正常,但我无法让 collection_select 做同样的事情?

如果我在 text_field_tag 中输入 1,我会生成 "search"=>"1" 作为参数的一部分,但是如果我从 [=34] 中输入 select =] 我明白了... {"utf8"=>"✓", "search"=>{"search"=>"1"},...

index.html.erb

 <h1>Students#index</h1>
<p>Find me in app/views/students/index.html.erb</p>

<%= form_tag students_path, :method => 'get' do %>
  <%= collection_select :search ,  :search.to_s, Tutor.all, :id, :name, prompt: true %>
  <%= submit_tag "search" %>
<% end %>

<% @students.each do |n| %>
  <li>
    <%= link_to n.first_name, student_path(n) %>
    <%= n.surname %> ..tutor is...
    <%= n.tutor.name %>
  </li>
 <% end %>

<%= params.inspect %>

<%= form_tag(students_path, :method=> "get", id: "search-form") do %>
  <%= text_field_tag :search, params[:search], placeholder: "Search Students" %>
  <%= submit_tag "Search", :name => nil %>
<% end %>

student.rb

class Student < ActiveRecord::Base
  belongs_to :tutor

  def self.search(search)
    where("tutor_id LIKE ?","%#{search }%")
  end
end

students_controller.rb

class StudentsController < ApplicationController
  def index
    if params[:search]
      @students = Student.search(params[:search])
    else
      @students = Student.all
    end
  end

这就是 collection_select 的工作方式。 collection_select 的第一个参数是 object 而不是 method ,所以你的参数看起来像那样。

params[:search] 更改为 params[:search][:search] 应该可以解决您的问题。

class StudentsController < ApplicationController
  def index
    if params[:search][:search]
      @students = Student.search(params[:search][:search])
    else
      @students = Student.all
    end
  end
end