Reputation: 407
I the following models
class Company < ActiveRecord::Base
attr_accessible :name, address, ........
has_many :employees
end
class Employee < ActiveRecord::Base
attr_accessible :firstname, :lastname, :company_id, .............
belongs_to :company
end
I have a string q and would like to select all the employees whos firstname lastname or company.name are like q, something along the line of this query non working query
Employee.where("firstname like ? or lastname like ? or company.name like ?", q,q,q)
What is the best way to achieve this with rails?
Upvotes: 2
Views: 1039
Reputation: 3741
as mentioned in this great answer, the way to go here is by using a search gem rather than an SQL.
the leading candidate is Thinking Sphinx.
another useful answer from the same thread would be: https://stackoverflow.com/a/4037835/690866 there he shows what you wanted to achieve, if i understand correctly..
hope it helps.
Upvotes: 0
Reputation: 7810
Try this one:
Employee.joins(:company).where("employees.firstname like ? or employees.lastname like ? or companies.name like ?", '%q%', '%q%', '%q%')
Upvotes: 6