user266003
user266003

Reputation:

Making a query by different columns with the same value

I need to make a query in Rails 4 where I want to filter to 2 different columns or fields by "OR". How can I do that? I only know how to query using one fields and different values.

MyModel.where(my_field: ["var1", "var2"])

But I want to use different columns and the same value and "OR".

Upvotes: 2

Views: 76

Answers (2)

jeffdill2
jeffdill2

Reputation: 4114

This would work for you:

MyModel.where(
 {some_field: "value"} | 
 {some_other_field: "value"}
)

String interpolation, as mentioned in Bryan's answer, is also perfectly valid. However, this is my preferred method for a couple of reasons:

  1. It's very readable.
  2. It's easy and clean to add more fields, if you decide you need to search for a particular value across 4 fields instead of 2, while still maintaining readability.

Upvotes: 0

Bryan Oemar
Bryan Oemar

Reputation: 926

How about doing something like this:

MyModel.where("my_field=? OR my_second_field=?", 'test', 'test')

Also for reference see section 2.2 Array Conditions: http://edgeguides.rubyonrails.org/active_record_querying.html

Upvotes: 2

Related Questions