如何在rails中使用like子句查询?
How to use like clause query in rails?
我想在搜索关键字时获得 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'
当我键入此内容时,http://localhost:3000/employees/showemployees?str=samplename,记录的 json 格式应该出现,但我收到此错误消息
undefined method `employees' for #<Class:0x8e38900>
app/controllers/employees_controller.rb:6:in `showemployees'
第 6 行有这段代码
render json: @employee = Employee.where(Employee.employees[:fname].matches("%#{str}%")) or
你可以链接where查询,但是这个AND
每个where查询结果
Employee.where('fname LIKE ?', "%#{str}%").where('lname LIKE ?', "%#{str}%").where('mname LIKE ?', "%#{str}%").where('username LIKE ?', "%#{str}%").where('id LIKE ?', "%#{str}%")
或使用OR
子句
Employee.where('fname LIKE ? OR lname LIKE ? OR mname', "%#{str}%", "%#{str}%", "%#{str}%")
我想在搜索关键字时获得 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'
当我键入此内容时,http://localhost:3000/employees/showemployees?str=samplename,记录的 json 格式应该出现,但我收到此错误消息
undefined method `employees' for #<Class:0x8e38900>
app/controllers/employees_controller.rb:6:in `showemployees'
第 6 行有这段代码
render json: @employee = Employee.where(Employee.employees[:fname].matches("%#{str}%")) or
你可以链接where查询,但是这个AND
每个where查询结果
Employee.where('fname LIKE ?', "%#{str}%").where('lname LIKE ?', "%#{str}%").where('mname LIKE ?', "%#{str}%").where('username LIKE ?', "%#{str}%").where('id LIKE ?', "%#{str}%")
或使用OR
子句
Employee.where('fname LIKE ? OR lname LIKE ? OR mname', "%#{str}%", "%#{str}%", "%#{str}%")