如何在Rails中使用Like子句查询? [英] How to use like clause query in rails?

查看:122
本文介绍了如何在Rails中使用Like子句查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在搜索关键字时获取数据的json格式,所以我使用LIKE子句并像这样进行查询

I wanted to get a json format of the data when searching for the keyword so I use LIKE clause and query like this

"select * from employees where fname like ? or mname like ? or lname like ? or username like ? or id like ?", str, str, str, str, str

但是我想使用rails对其进行编码.我的控制器中有此代码

but I want to code it using rails. I have this code in my 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

and this code in my config/routes.rb

get 'employees/showemployees'
root :to => 'employees#new'
resources :employees
post 'employees/update_info'

当我键入此内容时, http://localhost:3000/employees/showemployees?str = samplename ,记录的json格式应该出现,但我收到了此错误消息

when i type this, http://localhost:3000/employees/showemployees?str=samplename, a json format of the record should appear yet I got this error message

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

推荐答案

您可以将查询链接到哪里,但是每个AND哪里查询结果

You can chain where queries, but this AND each where query results

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}%")

这篇关于如何在Rails中使用Like子句查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆