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.
No, you’re mistaken. Actually, no queries are performed here.
The actual query is sent where you start retrieving data. That is, do something like
Until then you can safely chain criteria building methods (
where,order,selectand others).