2016-03-27 59 views
0

所以我試圖過濾一些基於collection_select下拉框的數據。rails collection_select params

我可以成功地使用text_field_tag過濾數據,所以我假設我的過濾器工作正常,但我不能讓collection_select做同樣的事情?

如果我在text_field_tag中輸入1,則會生成「search」=>「1」作爲參數的一部分,但是如果從collection_select中選擇,我會得到...「 {」utf8「=>」 ✓」, 「搜索」=> { 「搜索」=> 「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 

回答

0

這就是collection_select的工作方式。的collection_select第一個參數是一個對象不是方法,讓您的PARAMS像她那樣。

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 
+0

謝謝帕萬,那工作:-) – futureprogress