2

I'm having trouble joining the values for querying multiple values to one column. Here's what I got so far:

def self.showcars(cars)
    to_query = []
    if !cars.empty? 
      to_query.push cars
    end
    return self.find_by_sql(["SELECT * FROM cars WHERE car IN ( ? )"])
end

That makes the query into:

SELECT * FROM cars WHERE car IN (--- \n- \"honda\"\n- \"toyota\"\n')

It seems find_by_sql sql_injection protection adds the extra characters. How do I get this to work?

3 Answers 3

4

Do you really need find_by_sql? Since you're performing a SELECT *, and assuming your method resides on the Car model, a better way would be:

class Car < ActiveRecord::Base
  def self.showcars(*cars)
    where('car in :cars', :cars => cars)
    # or
    where(:car => cars)
  end
end

Note the * right after the parameter name... Use it and you won't need to write code to make a single parameter into an array.

If you really need find_by_sql, try to write it this way:

def self.showcars(*cars)
  find_by_sql(['SELECT * FROM cars where car in (?)', cars])
end
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, I'm joining legacy databases in my actual query so I went with find_by_sql. Anyway to make this work?
I edited my answer to provide you a find_by_sql alternative. Check it out.
Looks like I didn't even need to do any joining of passed values since they were already arrays. This is working now.
0

Try joining the to_query array into a comma separated string with all values in single quotes, and then passing this string as a parameter "?".

1 Comment

I've tried joining with comma separated and it does this - ('honda\', \'toyota'). Again seems like the sql injection is kicking in which will result with zero records because honda\ does not exist. There's gotta be a way to do this. Someone must have experienced this before.
0

Problem resolve.

def self.average_time(time_init, time_end)

    query = <<-SQL
                 SELECT COUNT(*) FROM crawler_twitters AS twitter WHERE CAST(twitter.publish AS TIME) BETWEEN '#{time_init}' AND '#{time_end}'
                  GROUP BY user) AS total_tweets_time;
    SQL

    self.find_by_sql(sanitize_sql(query))
  end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.