Reputation: 365
I have a requirement where I need to execute queries based on demand. In my code I have a param called, order_type. If the order_type is "current_day", I need to trigger a query
[order_date = ? and user_id = ? and country_id = ?, @order_date, @user_id, @country_id]
if the order_type is "past" I need to execute
[order_date < ? and user_id = ? and country_id = ?, @order_date, @user_id, @country_id]
I dont want to add an if else here as I have a couple of more queries are filtering based on order_type field. I have added a variable @comparator and set it as '<' if order_type is old and '=' when order_type is current, and made the query like this.
[order_date "+@comparator+" ? and user_id = ? and country_id = ?, @order_date, @user_id, @country_id]
But, this makes a threat of SQL injection. Please let me know what is the best way to handle this.
Thanks in advance.
Upvotes: 0
Views: 55
Reputation: 2675
@comparator will hold one of the values ['>', '<', '=', etc]
so write method which will check that comparator should be one among the values you mentioned in the array.If Method return true then proceed with your query or else reject it.
like this.
def comparator(comparator)
arr_set = ['>', '=']
arr_set.include?(comparator)
end
if comparator(@comparator)
execute_query
else
# throw error or do somthing
end
This will prevent sql injections
Upvotes: 1