I have a code structure like this:
if params[:one] && params[:two]
object = Something.where(:one => params[:one], :two => params[:two])
elsif params[:one]
object = Something.where(:one => params[:one])
elsif params[:two]
object = Something.where(:two => params[:two])
else
object = Something.all
end
Basically, two optional parameters in the URL that filter the query to be made. Can this be cleaner?
I’d write:
Notes:
Usually an empty param is also to be considered as non-existing. In this case:
Something.where(params.slice(:one, :two).select { |k, v| v.present? }).Strange as it may look, in your snippet you should write
object = if ..., it’s far more idiomatic being Ruby a language where conditionals are expressions and not statements.Don’t call
allas a no-op, you don’t have aActiveRecord::Relation(cool) anymore, but aArray(not so cool).where({})is perfectly fine.Naming is very important! If you see
objectyou think “single element” (which is not true here), if you seeobjectsyou think “collection”.If the param keys does not match DB columns: a lot of ways to do it, for example:
Or being just two attributes: