ruby_noobie
ruby_noobie

Reputation: 205

Check multiple conditions in Ruby on Rails search using AND / OR

My current method is as follows:

    def self.search(query)
     where("name like ?", "%#{query}%")
    end

How can I add additional attributes? For example, I can't get this to work but it shows what I want to do:

    def self.search(query)
     where("name like ? OR model like ? OR year like ?", "%#{query}%")
    end

Upvotes: 1

Views: 1616

Answers (3)

smathy
smathy

Reputation: 27971

The other answers will both work, but it's easier in these cases to use named placeholders, because then you won't have to specify the query multiple times:

def self.search query
  where( "name LIKE :query OR model LIKE :query OR year LIKE :query", query: "%#{query}%")
end

Update

In the comments Stefan suggested using HEREDOC for a long query, which is a great suggestion. I'd like to also offer how I'd produce this particular string.

Because it's basically the same thing repeated three times, and then joined with ORs I'd actually create a little loop to construct the string, like so:

query_string = %w[name model year].map{|n| n+" LIKE :query"}.join(" OR ")
where( query_string, query: )

That way if I want to add another field later then it's much simpler.

Upvotes: 3

Alejandro Babio
Alejandro Babio

Reputation: 5229

I think, you want to do this:

def self.search(query)
  where("name like ? OR model like ? OR year like ?", "%#{query}%", "%#{query}%", "%#{query}%")
end

If you are using like all the three fields must be strings.

Upvotes: 2

iceraj
iceraj

Reputation: 359

I think answer closes to your question is: def self.search(name,model) where [ "name like ? OR model like ?" , name, model] end

Upvotes: 1

Related Questions