运行带有变量

时间:2015-07-19 08:27:01

标签: javascript mysql ruby-on-rails ruby

是否可以在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");
}

这会创建我的所有选项,当我运行时 {j}中的var x = document.getElementById("frm1");,我可以获取用户为其搜索插入的值。

在我的模型中,我正在尝试创建一个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 = cuisine,l = lowerScore ...)。无论如何在rails中这样做了吗?

1 个答案:

答案 0 :(得分:2)

当然!您可以使用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指南:

http://guides.rubyonrails.org/association_basics.html http://guides.rubyonrails.org/active_record_querying.html

此外,无论您做什么,在不使用ActiveRecord接口的情况下,不要在SQL查询中使用来自用户的输入。您将打开自己的SQL注入攻击。见https://en.wikipedia.org/wiki/SQL_injection

相关问题