Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort movies alphabetically in Rails? [closed]

If you visit http://ccvideofinder.heroku.com/, it's a good example of what I'm referring to.

How can this be done in Rails? I was thinking maybe using case/when statements but after fooling around with IRB for some time I couldn't figure it out.


In the model:

class Movies < ActiveRecord::Base
  validates_presence_of :title

  def self.find_by_first_letter(letter)
    find(:all, :conditions => ['title LIKE ?', "#{letter}%"], :order => 'title ASC')
  end

end

In the controller:

@result = Movie.find_by_first_letter(params[:letter])
like image 636
Sonny Black Avatar asked Nov 05 '13 00:11

Sonny Black


2 Answers

# Simple Ordering    
@videos = Movie.order('title ASC')

# Implement the ordering outside of definition
@videos = Movie.find_by_first_letter('a').order('title ASC')

# Implement the order into your definition (as in example below)
@videos = Movie.find_by_first_letter('a')

Documentation for ActiveRecord Querying can be found: http://guides.rubyonrails.org/active_record_querying.html#ordering


If you wish to implement the order into your find_by_first_letter definition, then you can simply chain the .order() function as the following:

class Movie < ActiveRecord::Base
  validates_presence_of :title

  def self.find_by_first_letter(letter)
    where('title LIKE ?', "#{letter}%").order('title ASC')
  end
end
like image 149
Michael Lynch Avatar answered Oct 18 '22 22:10

Michael Lynch


I can't understand why are you not using query chaining:

Movie.where('title LIKE ?', "a%").order(:title)

But still better, create a scope as Michael Lynch said, it will increase your code reusability.

Actually your code is giving a deprecation warning. You must check for it in your Rails server terminal window. Although it's working it's not a good idea to let that go unchecked.

DEPRECATION WARNING: Calling #find(:all) is deprecated. Please call #all directly instead. You have also used finder options. These are also deprecated. Please build a scope instead of using finder options. (called from irb_binding at (irb):1)

like image 45
Akshat Avatar answered Oct 18 '22 21:10

Akshat