Sunday, November 8, 2009

Product.find: dynamic condition use in active record find

I've had some fighting time with active record. Although it's really not hard, I had some trouble getting it done nicely in Ruby/Rails. I'm learning... I've seen more people having this type of problem while googling, so I wanted to share my little experience.

I needed a list of products which could be filtered by two ways. 1. I needed to filter "All" or the "Not yet offered" products (via a select box), and 2. additionally I wanted to provide a "contains" edit field.

The expected result was that the list would be regenerated when something changed. In the case of the edit field, I wait 0,6 seconds before starting the request. The combination provides an intuitive filtering mechanism.

The following code snippet is my current basic solution for this:

conditions = []

# Contains field has value
conditions << "(title LIKE '%#{params[:prod_search]}%' OR code LIKE #{params[:prod_search]}%')" unless params[:prod_search].empty?

# Non-offered selected
conditions << "id NOT IN (SELECT distinct(product_id) from shop_offers)" if params[:prod_filter] == "non_offered"

@products_avail = Product.find(:all, :conditions => conditions.join(" AND ")

No comments:

Post a Comment