Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在rails中使用like子句查询?_Ruby On Rails_Json_Ruby_Sql Like_Clause - Fatal编程技术网

Ruby on rails 如何在rails中使用like子句查询?

Ruby on rails 如何在rails中使用like子句查询?,ruby-on-rails,json,ruby,sql-like,clause,Ruby On Rails,Json,Ruby,Sql Like,Clause,我希望在搜索关键字时获得json格式的数据,所以我使用LIKE子句和如下查询 "select * from employees where fname like ? or mname like ? or lname like ? or username like ? or id like ?", str, str, str, str, str 但我想用rails编写代码。我的控制器中有这个代码 def showemployees str = params[:str] render js

我希望在搜索关键字时获得json格式的数据,所以我使用LIKE子句和如下查询

"select * from employees where fname like ? or mname like ? or lname like ? or username like ? or id like ?", str, str, str, str, str
但我想用rails编写代码。我的控制器中有这个代码

def showemployees
  str = params[:str]
  render json: @employee = Employee.where(Employee.employees[:fname].matches("%#{str}%")) or
    (Employee.employees[:mname].matches("%#{str}%")) or
    (Employee.employees[:lname].matches("%#{str}%")) or
    (Employee.employees[:id].matches("%#{str}%"))
end
这段代码在我的config/routes.rb中

get 'employees/showemployees'
root :to => 'employees#new'
resources :employees
post 'employees/update_info'
当我输入这个时,记录的json格式应该会出现,但我收到了这个错误消息

undefined method `employees' for #<Class:0x8e38900>
app/controllers/employees_controller.rb:6:in `showemployees'

您可以链接where查询,但这是
每个where查询的结果

Employee.where('fname LIKE ?', "%#{str}%").where('lname LIKE ?', "%#{str}%").where('mname LIKE ?', "%#{str}%").where('username LIKE ?', "%#{str}%").where('id LIKE ?', "%#{str}%")
或使用
子句

Employee.where('fname LIKE ? OR lname LIKE ? OR mname', "%#{str}%", "%#{str}%", "%#{str}%")

谢谢,我消除了这个错误,但是它返回null,尽管我的数据库中有一个关键字为entered的记录。你可以减少重复:
Employee.where('fname-LIKE:q或lname-LIKE:q或mname-LIKE:q',q:%{str}%')
。但是不幸的是,
str
中的“%”和“”字符将不会被转义!在
“%#{str}%”
中使用这些字符之前,需要手动转义它们。你可以像这样做:
ActiveRecord::Base.send(:sanitize\u sql\u like,str)
请注意。当使用布尔逻辑时,只应使用后者。(虽然这不是你的问题。)
Employee.where('fname LIKE ? OR lname LIKE ? OR mname', "%#{str}%", "%#{str}%", "%#{str}%")