Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use like clause query in rails?

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

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

and this code in my config/routes.rb

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

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'

where line 6 has this code

render json: @employee = Employee.where(Employee.employees[:fname].matches("%#{str}%")) or
like image 718
MAC Avatar asked Feb 10 '23 13:02

MAC


1 Answers

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 to use OR clause

Employee.where('fname LIKE ? OR lname LIKE ? OR mname', "%#{str}%", "%#{str}%", "%#{str}%")
like image 127
Sonalkumar sute Avatar answered Feb 13 '23 21:02

Sonalkumar sute