Search code examples
ruby-on-rails-3.1meta-search

Return 0 records metasearch


I am on Rails 3.1 and I am using the Ransack Gem. This is what I have in my controller:

@q = Person.search(params[:q])
@people = @q.result 

This is what I have in my view:

<%= search_form_for @q do |f| %>

  <label>Given Name:</label>
  <%= f.text_field :given_name_cont %>

  <label>Family Name:</label>
  <%= f.text_field :family_name_cont %>

  <%= f.submit %>

<% end %>

This works well and is per the Ransack documentation. However, if my search form does not contain any parameters (ie nothing specified to search) it returns ALL records. What I want to have happen is NO records returned.

My Ruby is pretty weak so can someone show me how to cleanly have @people return an empty array if there is no params[:q] or params[:q] does not specify any search criteria (ie the user submitted an empty form).

Essentially my question is the same as this Metasearch question on StackOverFlow, but the solution doesn't seem to work for Ransack as it complains "search_attributes" is not an available method.

It's important that it returns 0 records with no params submitted and with empty params submitted. Any notes explaining why your code works would be good to. Thanks.


Solution

  • You could replace your controller code with:

    if !params[:q].blank?  # nil.blank? and [].blank? are true
      @q = Person.search(params[:q])
      @people = @q.result 
    else
      @people = []
    end