2

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?

2 Answers 2

6

Try this one:

Employee.joins(:company).where("employees.firstname like ? or employees.lastname like ? or companies.name like ?", '%q%', '%q%', '%q%')
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.