Reputation: 25
I'm working with Ruby on Rails, trying to get my search bar to display the results. I've tried searching for similar issues, but most already had search working and weren't getting it to work right.
in my html I have:
<%= form_tag users_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
<div class="scrollBox">
<%= will_paginate%>
<ul>
<% @users.each do |user| %>
<li>
<%= link_to user.name, user, {:class=>"signout-style"} %>
</li>
<% end %>
</ul>
<%= will_paginate %>
</div>
In my users controller I have:
def index
@users = User.paginate(page: params[:page])
@searches = User.search(params[:search])
end
In my users model I have:
def self.search(search)
if search
find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
else
find(:all)
end
end
I was using the railscast episode #37 Any help is appreciated!
Upvotes: 1
Views: 1046
Reputation: 53018
Update the index
action as below:
def index
@users = User.search(params[:search]).paginate(page: params[:page])
end
Currently, you are storing the search results in instance variable @searches
with this line:
@searches = User.search(params[:search])
BUT in your view you are accessing @users
which is set as @users = User.paginate(page: params[:page])
. So, you always see all the users in the view and not the searched users.
UPDATE
As you are using Rails 4.0.2
, I would suggest you to refactor your search
method as below:
def self.search(search)
if search
where('name LIKE ?', "%#{search}%")
else
all
end
end
Upvotes: 1