sybind
sybind

Reputation: 3588

find all records where two conditions are true

I'm trying to find all records where two conditions are true. For example:

ruby-1.8.7-p302 > Person.all
 => #<Person name: "Jane", city: "Green Bay", state: "Wisconsin", single: true>
 => #<Person name: "Dick", city: "Madison", state: "Wisconsin", single: false> 
 => #<Person name: "Tom", city: "Milwaukee", state: "Wisconsin", single: true>

I want to get the "Jane" and "Tom" records. I'm trying this, but it doesn't work:

Person.find_all_by_state("Wisconsin").find_all_by_single(true)

Upvotes: 14

Views: 27440

Answers (3)

Shivam Tripathi
Shivam Tripathi

Reputation: 51

Example using a OR condition:

model_name.where("field_1 = ? OR field_2 = ?", params[:search_string],  params[:search_string])

Upvotes: 5

Ryan Bigg
Ryan Bigg

Reputation: 107718

I would go with dmarkow's answer, but as a little bit of additional trivia you can also do this:

Person.find_all_by_state_and_single("Wisconsin", true)

Chain as many fields using _and_ as desired. The where syntax is much neater than this however.

Upvotes: 9

Dylan Markow
Dylan Markow

Reputation: 124419

Person.where(:state => "Wisconsin", :single => true)

Upvotes: 43

Related Questions