ruby on rails - dynamically insert greater than > | less than < | equals to = operators into a query -
my app allows filtering via get.
www.mysite.com/rating=5 www.mysite.com/rating>5 www.mysite.com/rating<5 i can split params[:filter] into:
column(filter)value(5)operator(=,>,<)
so after queried laptop model , did basic ordering, filter results if set.
if params[:filter] != "all" . . case operator when "=" laptops = laptops.where("laptops.rating = ?", value) when ">" laptops = laptops.where("laptops.rating > ?", value) when "<" laptops = laptops.where("laptops.rating < ?", value) end end i wondered if there way add operator dynamically similar value. when add >=, <= code gets repeated 5 times!
i tried:
laptops.where("laptops.rating ? ?", operator, value) but added operator string, naturally resulted in error
syntax error: near "laptops.rating '>' '6'"
any ideas how can make code more dry?
using postgresql
you try:
if params[:filter] != "all" . . # if statement makes sure operator 1 of valid operators if ["<",">",">=","<=","="].include? operator laptops = laptops.where("laptops.rating #{operator} ?", value) end end using ? in query tells rails parameter should escaped before inserted query practice. - if first sanitze / validate operator variable make sure contains valid characters should fine inserting directly query.
that's why rails tells you:
syntax error: near "laptops.rating '>' '6'" because > character escaped '>' , no longer valid sql-operator.
Comments
Post a Comment