How to set a 0 result in meta_search before user pressing a search button
I'm using a meta_search on my rails 3 app. By default (before pressing a search button) meta_search returns all elements of开发者_JAVA技巧 searching model. and I want to set 0 result before user pressing a search button or if search params is blank.
I am using meta_search as follows:
def index
@search = Article.search(params[:search])
if params[:search].blank?
@places = nil
else
@places = @search.all
end
end
What is the best way to set a 0 result if search params is blank ?
Thanks
I don't think that's something that Meta Search really provides out of the box but you can always cheat it.
def index
@search = Article.search(params[:search].presence || {:id_lt => 0})
@places = @search.all
end
In my opinion, your solution is good enough. It's clear about what it's doing and it doesn't access the database unnecessarily. But the code can be improved to:
def index
@search = Article.search(params[:search])
@places = @search.search_attributes.values.all?(&:blank?) ? [] : @search.all
end
Checking the hash for blank is not the way to do it. A hash like {'name_contains' => ''}
, which is what you get if the form submitted is blank, will return false
.
Also it's better to set @places
to an empty array rather than nil
. This way you don't have to check for nil
and your loop will still work.
精彩评论