How can you conditionally build an ActiveRecord query in Rails?

I am trying to create a search results page in my rails application (still noob) and I cannot figure out how to build a query on rails.

For example, if there are no parameters, I want to return all the results. If the user passes from 1 to n additional parameters in the search form, I want to add them to the request.

Further, if they have a sort of "price desc" or "year_built desc" or even a combination of both.

Finally, use will_paginate to separate the results.

# default to all listings @listings = Mls.all @listings.where("listing_price > ?", params[:listing_price]) unless params[:listing_price].blank? # ... bunch of other search options ... @listings.where("property_type = ?", params[:property_type]) unless params[:property_type].blank? # order @listings.order("some order by param") if some sort param @listings.order("some order by param") if some other sort param # paginate results @listings.paginate(:page => params[:page]) 

Is there a way for Rails to do this?

+6
source share
2 answers

Have you seen the (revised) episode of Railscasts in advanced search? Here is the link: http://railscasts.com/episodes/111-advanced-search-form-revised

The main idea is to create a Search resource that will process the search parameters submitted through the form and in the background search by the model in question (in your case, Mls )

Thus, instead of checking the controller for the presence of certain parameters (for example, params[:listing_price] ), you can process the conditions in your search model (models / search.rb):

 def find_listings listings = Mls.order(:name) listings = listings.where("listing_price > ?", listing_price) if listing_price.present? # ... more condition checking listings end 
+21
source

All Articles