Last Updated: February 25, 2016
·
308
· gouthamkgh

.where with conditionals in Ruby on Rails

A couple of days ago, I was stuck in a situation where I had to query the database to find a set of songs between two 'total number of times played' ranges. While we use the where statement for this in Ruby, most of the times we do it with an equality query (Ex: find a song where id = 10, find all playlists where rating = 5)

If we want to use the where statement with inequalities (Ex: find all playlists with rating between 4 and 5), this is how we do it:

def get_playlists_within_rating_range( min_rating, max_rating)
    playlists.where("rating >= :min_rating and rating <= :max_rating", :min_rating => min_rating, :max_rating => max_rating)
   # do some stuff
end