Find by multiple conditions in rails

19,189

Solution 1

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.

Solution 2

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

Solution 3

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.

Solution 4

You can do it using:

Movie.where(:rating => ['R','PG'])
Share:
19,189
18bytes
Author by

18bytes

A hacker.

Updated on July 15, 2022

Comments

  • 18bytes
    18bytes almost 2 years

    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.

  • miked
    miked over 11 years
    @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!
  • Mischa
    Mischa over 11 years
    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.