问题
I'm using a meta_search on my rails 3 app. By default (before pressing a search button) meta_search returns all elements of 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
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/5827910/how-to-set-a-0-result-in-meta-search-before-user-pressing-a-search-button