2

I'm attempting to create a search method on one of my Active Record models.

I want users to be able to search for a record in the database.

I know I can do something like this: Model.where('field like ?', "%#{query}%')

But it's not just one field, it's two fields (first name and last name). But I don't want to search them separately, I want to concatenate first name and last name and search where the concatenated field is like the search query.

Can this be done with Active Record similar to how SQL fields can be concatenated? What's the best solution?

1

2 Answers 2

1

Create a class method in your model as shown:

def self.search_by_full_name(query)
  where("CONCAT_WS(' ', first_name, last_name) LIKE ?", "%#{query}%")
end

But in Rails, it is more common to declare a scope rather than a class method in such scenarios, like this:

scope :search_by_full_name ->(query) { where("CONCAT_WS(' ', first_name, last_name) LIKE ?", "%#{query}%") }
0

You can use the same where method with different fields. For example

Model.where(first_name: "Jonathan", last_name: "Smith")

That will give you all the relations (in Rails 4) where first_name AND last_name match.

If you want a query more dynamic (for example if you want to use both: OR, AND), you can use find_by_sql this:

Person.find_by_sql("SELECT * FROM people WHERE first_name = ? OR first_name = ? AND last_name = ?", first_name1, first_name2, last_name)

But it might require more specific code-chemistry for constructing such a SQL query-string

Your Answer

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