0

我正在尝试在带有 Rails 查询帮助器方法的 Rails 应用程序中使用以下 sql 语句。在原始(非 Rails)应用程序中,此 sql 的结果是使用任何字母对某人的姓名进行模糊搜索。例如,如果您在搜索框中输入“a”,它将返回在某处包含字母“a”的每个人的姓名。“Marissa Jones”和“Andrea Barfs”都可以匹配。

      "select e.id, e.firstName, e.lastName, e.title " .
      "from employee e left join employee r on r.managerId = e.id " .
      "WHERE UPPER(CONCAT(e.firstName, ' ', e.lastName)) LIKE :name " .
      "group by e.id order by e.lastName, e.firstName";

我尝试使用一些 Rails 活动记录查询接口帮助方法来翻译该 sql 语句。(我没有尝试从上面的 sql 中包含“join”,因为它似乎对于模糊搜索或我的应用程序的目的没有必要)。有一个用户提供的参数:query

员工控制器.rb

respond_to :json
 ...
def getEmployeesByName

    query = Employee.select("id, firstname, lastname, title")
    q = "%#{params[:query]}%"
    query.where("UPPER(CONCAT(firstName, ' ', lastName)) LIKE ?", q).to_sql
    query.group("id")
    query.order("lastname", "firstname")

    respond_with query.all 

end 

当我尝试我的代码时,它会返回数据库中的所有 5 名员工,即使他们的名字中没有字母“a”。这是服务器中显示的 sql,例如,当我在搜索框中输入“a”时。

  Processing by EmployeesController#getEmployeesByName as JSON
  Parameters: {"query"=>"a"}
  Employee Load (0.1ms)  SELECT id, firstname, lastname, title FROM "employees" 

所以我的行动的最后四行似乎被忽略了

    query.where("UPPER(CONCAT(firstName, ' ', lastName)) LIKE ?", q).to_sql
    query.group("id")
    query.order("lastname", "firstname")
    respond_with query.all 

谁能解释我做错了什么。先感谢您。

4

2 回答 2

0

I got it to include the other sql in the query by doing

respond_with Employee.select("id, firstname, lastname, title").where("UPPER(CONCAT(firstName, ' ', lastName)) LIKE ?", params[:query])

It turns out that sqlite3 doesn't have a CONCAT function but that's a separate issue.

于 2013-01-16T23:33:43.810 回答
0

query is being assigned an instance of Employee by the first line. You are then calling where, group, and order on the class Employee via the instance, but ignoring the result in every case. Finally, you are calling Employee.all via the instance, and inspecting the result, which correctly includes all records. Try something like:

respond_with Employee.where("UPPER(CONCAT(firstName, ' ', lastName)) LIKE ?", q).group("id").order("lastname", "firstname")
于 2013-01-16T23:34:09.067 回答