rails - how to get search display blank when search field is blank
I am using metasearch. I want to search for friends using email.
In my users controller:
def index
@search = User.search(params[:search])
@users = @search.all
end
In my view:
<%= form_for @search do |f| %>
<div class="prepend-top field">
<%= f.label("Primary email address") %></br>
<%= f.text_field(:email_matches) %>
</div>
<div class="prepend-top field">
开发者_开发问答<%= f.label("School email address") %></br>
<%= f.text_field(:school_email_matches) %>
</div>
<div>
<ul>
<% if params[:search].blank? %>
Your search results here.
<% else %>
<% @users.each do |user| %>
<li class="box round">
<%= user.name %></br>
</li>
<% end %>
<% end %>
</ul>
</div>
The way it is now, the results are displayed on an adjacent column on the same page. I am trying to have it so that if the search form is blank then it returns a blank search.
Problems:
When I go to the page initially, the search results side is blank and does say "Your search results here". But, when I just click on the search button without putting anything in the search fields, it returns a list of all the users on the search result column. How do I make it so that a blank search form truly returns a blank page?
How do I go about making it so that it shows "No results for your search criteria"? if there are no matches for the particular search?
Thanks.
Part of your problem is happening because when you search for an empty string, your search function returns all your users.
So, in your controller, you could do:
def index
if params[:search]
empty_search = params[:search].keep_if {|k, val| !val.blank?}.empty?
else
empty_search = true
end
if empty_search
# no search was submitted, or search params are all blank
@search = ""
@users = []
else
# a search was submitted
@search = User.search(params[:search])
@users = @search.all
end
end
(not sure about the exact terminology for the condition, but basically, if you're passing an empty string or nothing, you should run the 'else' piece of the code).
In the view, you could do:
<% if @search.blank? %>
Your search results here.
<% else %>
<% if @users.blank? %>
No results for you
<% else %>
<ul>
<% @users.each do |user| %>
<li class="box round">
<%= user.name %></br>
</li>
<% end %>
</ul>
<% end %>
</ul>
Would that work?
精彩评论