【问题标题】:How to use like clause query in rails?如何在rails中使用like子句查询?
【发布时间】:2015-03-30 11:59:42
【问题描述】:

我想在搜索关键字时获得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

【问题讨论】:

标签: ruby-on-rails json ruby sql-like clause


【解决方案1】:

你可以链接 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}%")

【讨论】:

  • 谢谢,我摆脱了这个错误,但它返回 null 虽然我的数据库有一个输入关键字的记录
  • 您可以使用named placeholders: Employee.where('fname LIKE :q OR lname LIKE :q OR mname LIKE :q', q: "%#{str}%") 减少重复。
  • 但很遗憾,str 中的“%”和“_”字符不会被转义!在"%#{str}%" 中使用它们之前,您需要手动转义这些字符。你可以这样做:ActiveRecord::Base.send(:sanitize_sql_like, str)
猜你喜欢
  • 2017-04-22
  • 2021-08-10
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
  • 1970-01-01
  • 2014-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多