2

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

Talgat Medetbekov
  • 3,741
  • 1
  • 19
  • 26

2 Answers2

2

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
aNoble
  • 7,033
  • 2
  • 37
  • 33
1

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.

htanata
  • 36,666
  • 8
  • 50
  • 57
  • Yeah you are very right about setting nil object to instance variable `@places`, and thank you very much! I really appreciate this help ))) – Talgat Medetbekov Apr 29 '11 at 14:27