我有一个Rails SQL查询,如下所示:
searchSQL = "SELECT a.id, a.asset_id, a.name, a.serial_number, a.category_id, a.status_id, a.user_id, a.location_id" +
" from assets a where a.asset_ID LIKE '%"
"%' OR a.name LIKE '%" + @searchBox + "%'" +
"OR a.serial_number LIKE '%"+@searchBox+"%'" +
"UNION " +
"SELECT a.id, a.asset_id, a.name, a.serial_number, a.category_id, a.status_id, a.user_id, a.location_id" +
" from assets a, users u where a.user_id = u.id AND (u.first_name LIKE '%" + @searchBox +
"%' OR u.last_name LIKE '%" + @searchBox + "%')" +
"order by asset_id ASC"
正如你所看到的,它重复了searchBox Value,我想用paramatized SQL对它进行sanatize,但是我不知道如何在每个中添加相同的值?不重复自己。
答案 0 :(得分:0)
您可以像这样使用rails'字符串插值:
searh_term = "%#{@searchBox}%"
searchSQL = "SELECT a.id, a.asset_id, a.name, a.serial_number, a.category_id, a.status_id, a.user_id, a.location_id
from assets a
where a.asset_ID LIKE '%%' OR a.name LIKE ?
OR a.serial_number LIKE ?
UNION
SELECT a.id, a.asset_id, a.name, a.serial_number, a.category_id, a.status_id, a.user_id, a.location_id
from assets a, users u
where a.user_id = u.id AND (u.first_name LIKE ?
OR u.last_name LIKE ?)
order by asset_id ASC"
results = Model.find_by_sql(searchSQL, search_term, search_term, search_term, search_term)
你必须为每一个传递一个值吗?在您的查询中。 请注意,您可以避免连接字符串,ruby支持多行字符串文字。