问题
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.
回答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.
回答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
回答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.
回答4:
You can do it using:
Movie.where(:rating => ['R','PG'])
来源:https://stackoverflow.com/questions/11829850/find-by-multiple-conditions-in-rails