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

时间:2015-03-30 11:59:43

标签: 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编写代码。我的控制器中有这个代码

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

1 个答案:

答案 0 :(得分:6)

您可以将查询链接到哪里,但查询结果

的每个AND
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}%")