Nick Ginanto
Nick Ginanto

Reputation: 32130

Scope chaining with optionally parameters

currently I have the following type of code

scope :scope1, lambda{|param| where(param1: params)}
scope :scope2, lambda{|param| where(param2: params)}

and in the controller I would do

results = Model.some_other_scope

if !params[:param1].blank?
 results = results.scope1(params[:param1])
end

if !params[:param2].blank?
 results = results.scope2(params[:param2])
end

this is not very efficient since it does several calls to DB instead of one.

Is there a way to chain these scopes so it will be disabled if the params don't exist?

results = Model.scope1(params[:param1]).scope2(params[:param2])

currently, chaining doesn't work because of the where clause doesn't return anything then the whole chain breaks

Upvotes: 0

Views: 59

Answers (1)

Marek Lipka
Marek Lipka

Reputation: 51151

Actually, ActiveRecord queries are evaluated lazily, so, simplyfying, this code produces only one DB call. So your problem doesn't really exist.

Upvotes: 2

Related Questions