If i use expression Model.find(1)
then rails executes it as prepared statement: SELECT "models".* FROM "models" WHERE "models"."id" = $1 LIMIT 1 [["id", 1]]
But when I use Model.where("id = ?", 1)
it executes without prepared statement: SELECT "models".* FROM "models" WHERE (id = 1)
How to force rails to use prepared statement in this case too?
i'm not sure you can.
But
Model.where(:id => 1)
Should generate a prepared statement. Fragment string works differently, so you can generate exactly what you need, in custom cases.
Edit :
Try this, i'm not sure it works, i can' test for now, but it looks like what you need :
Client.where("created_at >= :start_date AND created_at <= :end_date",
{:start_date => params[:start_date], :end_date => params[:end_date]})
More here: http://guides.rubyonrails.org/active_record_querying.html#conditions
In the placeholder section. Moreover date range works in the array format :
:date => date_begenning..date_end
Edit 2 : indeed you can, but i seems where don't support building this by hand.
You might build your prepared queries by hand :
exec_query(sql, name = 'SQL', binds = [])
There is also a bind method on your relation.
But both binds need that the value have a name method, they will crash if you give a fixnum, a hash, ect. I hadn't found any doc explaining how this works.
Bu for the where clause, as long it is of Class String, active ecord apply a .to_sql on it, so you don't get your prepared statement.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.