How to set a 0 result in meta_search before user pressing a search button

十年热恋 提交于 2019-12-02 06:09:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!