javascript - Rails 使用变量运行 sql 查询

标签 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");
}

这会创建我所有的选项,当我运行时
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 = Cuisine,l = lowerScore...)。有没有办法在 Rails 中做到这一点?

最佳答案

当然!您可以使用ActiveRecord的查询接口(interface)(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 接口(interface)的情况下在 SQL 查询中使用用户的输入。您将面临 SQL 注入(inject)攻击。请参阅https://en.wikipedia.org/wiki/SQL_injection

关于javascript - Rails 使用变量运行 sql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31499305/

相关文章:

php 文件返回错误转换为 Android GET 请求的 JSON

ruby-on-rails - PRNG 未播种错误

css - rails css 如何将两个按钮排成一行

javascript - 使用 jquery 设置不透明度

javascript - 如何将表单数据存储在ajax变量中?

java - Mysql 需要很长时间才能检索结果

ruby-on-rails - 尝试使用 rspec,但收到 rspec-core 2.2.1 已激活的错误,但我的 Gemfile 需要 rspec-core 2.1.0

javascript - 带有 JSON 对象的 ES6 getter setter

javascript - TypeScript 简单写下 "if"

php - MySQL 只更新表中的某些字段