簡體   English   中英

rails collection_select參數

[英]rails collection_select params

因此,我嘗試根據collection_select下拉框過濾一些數據。

我可以成功地使用text_field_tag過濾數據,因此我認為我的過濾器工作正常,但是我無法讓collection_select進行相同的操作嗎?

如果我在text_field_tag中鍵入1,則會生成“ search” =>“ 1”作為參數的一部分,但是如果我從collection_select中選擇,則會得到... {“ utf8” =>“✓”,“ 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的第一個參數是對象而不是方法 ,因此您的參數看起來像這樣。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM