Paritosh Singh
Paritosh Singh

Reputation: 6384

Rails: combine two queries into one

I am new to rails. Here is the following code with Foo as model object:

a = Foo
a = Foo.where(age: 18)
if params[:sort] == "desc"
  a = a.order("name desc") 
end

Here two queries are performed, I want to combine them to one or you can say i want to perform Foo.where(age=18).order("name asc")

Remember there can be the case when order is no needed i.e. params[:sort] is not equal to desc.

Please don't give solution like

if params[:sort] == "desc"
    a = a.where(age=18).order("name desc") 
else
    a = a.where(age=18)
end

as it makes code redundant and also for more parameters it might not work.

Upvotes: 0

Views: 351

Answers (3)

spas
spas

Reputation: 1934

If its that what you mean... A simple solution would be:

a.where(age: 18).order("name #{params[:sort] || 'asc'}")

So if params[:sort] is nil it will default to asc.

Upvotes: 0

davidrac
davidrac

Reputation: 10738

Actually your code will only execute one query. this is because in rails the calls to the database are only done once you access the result. So when you will write a.first (or something similar) it will make the DB call.

Upvotes: 0

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

No, you're mistaken. Actually, no queries are performed here.

a = Foo
a = Foo.where(age=18)
if params[:sort] == "desc"
  a = a.order("name desc") 
end

The actual query is sent where you start retrieving data. That is, do something like

a.each do |b|
  # do something with b
end

Until then you can safely chain criteria building methods (where, order, select and others).

Upvotes: 5

Related Questions