我想在搜索关键字时获取数据的 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 对其进行编码。我的 Controller 中有这段代码
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}%")
关于ruby-on-rails - 如何在 rails 中使用 like 子句查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29345690/