0
I’m working with JSON on Rails. Imagine the route:
# rota: pessoas.json
def index
@pessoas = Pessoa.all
end
That’s easy! But if I want to add an optional search by age I would have to have a condition:
# rota: pessoas.json?idade=30
def index
if params[:idade]
@pessoas = Pessoa.where("idade = ?", params[:idade])
else
@pessoas = Pessoa.all
end
end
This isn’t the end of the world, but it gets harder with more optional parameters:
pessoas.json
pessoas.json?idade=30
pessoas.json?sexo=m
pessoas.json?idade=30&sexo=m
What is the best (DRY) way to do this search in which the parameters are optional?
Great answer. The solution
Modelo.where( params.permit(...) )is really the best in the case of the search for equality =)– user7261