My idea for an #index method of a controller is to set things = Thing.all and then if there are filter params, check for them one by one and chain them on so that at the end, you're left with a single query to execute. But the following queries get executed as they are called:
def things_controller
def index
things = Thing.all #<-- db call #1
if params[:color]
things = things.where(color: params[:color]) #<-- db call #2
end
render json: things #<-- I would like to make a single db call here instead
end
end
How can I prevent multiple unnecessary db calls? Is there some convention for filter params that I should be using?