10

I want to search a table with multiple conditions in Rails. I am using Active record and rails version 3.1.0.

I have Movies object, and want to achieve the equivalent of the following in rails:

Select * from Movies where rating = 'R' OR rating = 'PG'

I tried the following but it does not work

@filtered = Movies.find(:all, :conditions => { :rating => 'R', :rating => 'PG' })

Can you please provide help to write an equivalent of SQL query mentioned above.

18bytes
  • 5,951
  • 7
  • 42
  • 69

4 Answers4

14

One way would be to build an "IN" condition with:

 @filtered = Movie.where(:rating => ['R', 'PG']).all

EDIT: I changed your class to "Movie" from "Movies". I assume that's what you will want.

miked
  • 4,489
  • 1
  • 17
  • 18
  • @Mischa - Very true, but that would of course depend on where and how one is using the statement, and I agree in most cases it's not necessary. For this answer, I wanted to explicitly return the resulting array and not an ActiveRecord::Relation object to avoid any possible confusion. Thanks for pointing that out though! – miked Aug 06 '12 at 14:24
  • I just think it looks strange to call `all` when you *don't* want all. If you are only doing it to return an array instead of an `ActiveRecord::Relation` it would IMO be clearer to just call `to_a` instead. – Mischa Aug 06 '12 at 14:34
10

In Rail 4, find with multiple conditions for example consider find Profile with first_name and last_name

Profile.find_by first_name: 'stack', last_name: 'flow' 

Finds the first record matching the specified conditions. There is no implied ordering so if order matters, you should specify it yourself. If no record is found, returns nil

Profile.find_by! first_name: 'stack', last_name: 'flow'

Like find_by, except that if no record is found, raises an ActiveRecord::RecordNotFound error.

For more information read Rails Finder Method

1: http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-find_byIn Rail 4, find with multiple conditions for example consider find Profile with first_name and last_name

Profile.find_by first_name: 'stack', last_name: 'flow' 

Finds the first record matching the specified conditions. There is no implied ordering so if order matters, you should specify it yourself. If no record is found, returns nil

Profile.find_by! first_name: 'stack', last_name: 'flow'

Like find_by, except that if no record is found, raises an ActiveRecord::RecordNotFound error.

For more information read Rails Finder Method

Deepak Kabbur
  • 774
  • 14
  • 25
5

i guess that would be

Movie.where("rating = ? OR rating = ?", 'R', 'PG')

have a look at the guides for more info: http://guides.rubyonrails.org/active_record_querying.html#conditions

i would recommend using an IN statement instead.

phoet
  • 18,688
  • 4
  • 46
  • 74
5

You can do it using:

Movie.where(:rating => ['R','PG'])
Mischa
  • 42,876
  • 8
  • 99
  • 111
rahduro
  • 83
  • 1
  • 7