How to sort movies alphabetically in Rails?

If you visit http://ccvideofinder.heroku.com/ , this is a good example of what I mean.

How can this be done in Rails? I thought maybe using case / when instructions, but after some time I wasn’t able to fool IRB.


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]) 
+6
source share
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') 

The documentation for an ActiveRecord request can be found: http://guides.rubyonrails.org/active_record_querying.html#ordering


If you want to implement an order in your find_by_first_letter definition, you can simply link the .order() function as follows:

 class Movie < ActiveRecord::Base validates_presence_of :title def self.find_by_first_letter(letter) where('title LIKE ?', "#{letter}%").order('title ASC') end end 
+14
source

I do not understand why you are not using the query chain:

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

But even better, create a scope, as Michael Lynch said, it will increase code reuse.

Actually your code gives an obsolescence warning. You should check this in the terminal window of the Rails server. Although this works, it is not a good idea that it should not be canceled.

DEPARTMENT WARNING: The #find (: all) call has expired. Instead, call #all. You also used search options. They are also out of date. Please create an area, not use search parameters. (called from irb_binding at (irb): 1)

+2
source

Source: https://habr.com/ru/post/957398/


All Articles