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])
# 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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With