views:

71

answers:

2

In my case,

I was storing the sql query in my database as text. I am showing you one record which is present in my database

Query.all

:id  => 1, :sql => "select * from user where id = #{params[:id]}"

str = Query.first

Now 'str' has value "select * from user where id = #{params[:id]}"

Here, I want to parsed the string like If my params[:id] is 1 then

"select * from user where id = 1"

I used eval(str). Is this correct?

+3  A: 

eval would do what you describe in this instance. However this is a very bad idea as it is susceptible to SQL injection. e.g. consider what would happen if params[:id] was equal to "1; delete * from queries".

If you need a way to store arbitrary queries in your database you would be better to store the parameterised version of the query:

select * from user where id = ?

and eval the parameters separately.

mikej
A: 

The SQL string stored in the database should use substitution parameters instead of Ruby code. The SQL string should be stored in the format shown below:

   str = "\"SELECT * FROM users WHERE id = ? AND type = ? \", 
              params[:id], params[:type]"

Now you can substitute the value for the parameters using the class method sanitize_sql_array and eval.

sql = eval("User.send(:sanitize_sql_array, [#{str}])")
users = User.find_by_sql(sql)
KandadaBoggu
sanitize_sql_array - how can I call this protected method?
Arun
Changed the code. Try again.
KandadaBoggu
You could call it from a method inside your Query class as that is a subclass of `ActiveRecord::Base` so the method will be visible. Alternatively, it can be called using `send` so your `eval` would be something like `eval("Query.send(:sanitize_sql_array, [#{str}])")`
mikej