Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: ActiveRecord db sort operation case insensitive

I am trying to learn rails [by following the SAAS course in coursera] and working with simple Movie table using ActiveRecord.

I want to display all movies with title sorted. I would like it to be sorted case insensitively.

I tried doing it this way:

Movie.all(:conditions => ["lower(title) = ?", title.downcase],:order => "title DESC")
=>undefined local variable or method `title' for #<MoviesController:0xb4da9a8>

I think it doesnt recognise lower(title) .

Is this the best way to achieve case insesisitve sort ?

Thanks!

like image 399
codeObserver Avatar asked Aug 04 '12 04:08

codeObserver


2 Answers

Use where and not all

Movie.where("lower(title) = ?", title.downcase).order("title DESC")

Don't really understand the sort though. Here you'll get all movies with lower title equalling to title.downcase. Everything is equal, how could you sort it by title desc ?

To sort reverse-alphabetically all movies by lowercase title :

Movie.order("lower(title) DESC").all
like image 182
Anthony Alberto Avatar answered Sep 22 '22 07:09

Anthony Alberto


You have to do this:

Movie.order("lower(title) DESC").all
like image 39
Dogbert Avatar answered Sep 19 '22 07:09

Dogbert