Rails SQL Bind
String concatenation is almost never the right answer when passing a parameter to an SQL query. For example, this is a bad idea:
sqltxt = "SELECT * FROM dept WHERE dname = '#{params['dname']}' "
@results = ActiveRecord::Base.connection.execute sqltxt
Replace it with a parameterized query like this:
sqltxt = "SELECT * FROM dept WHERE dname = ?"
@results = (ActiveRecord::Base.connection.raw_connection.prepare sqltxt).execute params['dname']
Adding some more code around the logic…
sqltxt = "SELECT * FROM dept WHERE dname = ?"
@results = []
st = ActiveRecord::Base.connection.raw_connection.prepare sqltxt
rset = st.execute params['dname']
# This will allow us to run a .count on @results
rset.each do |r|
@results.append r
end
st.close
Taking this example further, ensure that you limit the number of results of perform some kind of pagination on the query results.