So I am trying to filter some data based on a collection_select drop down box.
I can successfully use a text_field_tag to filter the data, so I assume my filter is working fine, but I can't get the collection_select to do the same?
If I type a 1 into the text_field_tag, I generate "search"=>"1" as a part of the parameters, but if I select from the collection_select I get... {"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
That is how collection_select work. The first parameter of collection_select
is an object not a method, so your params look like that.
Changing params[:search]
to params[:search][:search]
should solve your problem.
class StudentsController < ApplicationController
def index
if params[:search][:search]
@students = Student.search(params[:search][:search])
else
@students = Student.all
end
end
end