lundi 23 juillet 2018

conditionally compounding an SQL query in Ruby

I have several of if-statements that build a query string and a set of arguments, like so:

search_string = ""
arguments = []

if params["this_data"] != nil
    search_string << " AND this_data = ?"
    arguments << params["this_data"]
end
if params["that_data"] != nil
    search_string << " AND that_data = ?"
    arguments << params["that_data"]
end

This goes on and on until the search_string is built. Now I'm trying to run the query, and am not having much success. I am stuck on the following code, which is returning a syntax error:

Item.find_by_sql(["SELECT * FROM items WHERE thing IS NOT NULL ? ?", search_string, arguments])

I'm still plugging along at it, but so far, I'm not sure how I can compound this SQL string into something that returns a successful result.

Aucun commentaire:

Enregistrer un commentaire