问题描述
是否可以在rails中使用用户输入的变量运行sql查询?
我试图通过数据库搜索具有他们正在寻找的某些特征的餐厅(即美食,评分,邮政编码位置)。 这是我的html.erb作为参考。
<form id="frm1" action="form_action.asp">
Name: <input type="text" name="name" value="Antico Pizza"><br>
Lower Score: <input type=integer name="LowerScore" value=0>
Higher Score: <input type="integer" name="HigherScore" value=100><br>
Zipcode: <input type=integer name="Zipcode" value=30332><br>
<label for="Cuisine">Cuisine: </label>
<select name="Cuisine" id="Cuisine">
<%= @my_cuisines.each do|cuisine|%>
<option value=<%= cuisine.cuisine %> onclick="getCuisine()"><%= cuisine.cuisine %></option>
<% end %>
</select>
</form>
<button onclick="myFunction()">Search!</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("frm1");
}
这将创建我的所有选项,并在我运行时
var x = document.getElementById("frm1");
在javascript中,我能够获取用户为其搜索插入的值。
在我的模型中,我试图创建一个SQL语句,该语句将接受用户输入并遍历数据库并收集它们。
即
sql = "select * from restaurant, inspection
where restaurant.rid = inspection.rid
and cuisine ='#{c}'
and totalscore > '#{l}'
and totalscore < '#{h}'
and zipcode = '#{z}'"
#{x}
应该是用户变量(即c =美食,l = lowerScore ...)。
无论如何,在铁轨上这样做吗?
1楼
当然! 您可以使用ActiveRecord的查询界面(Arel)。
Restaurant.joins(:inspection).where(cuisine: c, zipcode: z, totalscore: l..h)
请注意,您将需要在餐厅和检验模型之间建立关联。
class Restaurant < ActiveRecord::Base
has_many :inspections, foreign_key: 'rid'
end
class Inspection < ActiveRecord::Base
belongs_to :restaurant, foreign_key: 'rid'
end
我建议您阅读有关以下主题的Rails指南:
另外,无论您做什么,都不要在不使用ActiveRecord接口的情况下在SQL查询中使用来自用户的输入。 您将可以接受SQL注入攻击。 参见