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

标签 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 对其进行编码。我的 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/

相关文章:

ruby-on-rails - 覆盖设计 SessionsController 销毁

ruby-on-rails - 基本的 Ruby 问题

ruby-on-rails - 两个相似的 rspec 测试,给出相反的结果

ruby-on-rails - 在 ruby​​ on rails 3.2 条件下过滤数组结果

javascript - 输入 ID 时,将图像添加到来自 json 文件的警报中

mysql - Ruby:如何通过 SSH 隧道返回 MySQL 查询?

javascript - 在 Rails 中提交表单,无需重新加载页面

ruby-on-rails - 如何使用 Jammit + Heroku + Cloudfront 服务 GZipped Assets

java - 如何使用 Jackson 将 Object 类发送到服务器?

javascript - 使用 d3.js v.4 解析日期