Optimus Pette
Optimus Pette

Reputation: 3400

Active Record query when some conditions are absent

I have the following hash conditions for retrieving products from the database:

@products = Product.where(category: @category, color: params[:color], brand_id: params[:brand], size: params[:size]).

Is there a way to get the query result when one or more of the conditions are not supplied, for example if params[:color] is absent, how can i retrieve the products with the other conditions?, or how can i restructure the conditions to achieve this?

Upvotes: 1

Views: 163

Answers (4)

mjnissim
mjnissim

Reputation: 3112

I'm going to base myself on techvineet's answer (editing was becoming messy).

Try this:

# This line throws away the :action and :controller arguments
params.except!(:action, :controller) # notice the ! now
params.delete_if {|k,v| v.nil?} # throw out any empty args
params[:category] = @category
@products = Product.where(params)

Upvotes: 2

techvineet
techvineet

Reputation: 5111

You could also use something like this:-

params.except(:action, :controller)
params[:category] = @category
@products = Product.where(params)

Upvotes: 2

KappaNossi
KappaNossi

Reputation: 2706

You can build your query using conditions like this:

product_scope = Product.where(:category => @category)
product_scope = product_scope.where(:color => params[:color]) if params[:color]
# (...)

@products = product_scope.all

That way, only the valid and present conditions are being added to the scope. Or you could build a hash with your options in a similar way and add only the keys with valid params, then call Product.where(conditions_hash).all

Upvotes: 1

Oleg Haidul
Oleg Haidul

Reputation: 3732

You can try Periscope gem

Or Ransack

Upvotes: 1

Related Questions