如果你访问
http://ccvideofinder.heroku.com/,这是我所指的一个很好的例子.
如何在Rails中完成?我在考虑使用case / when语句但是在与IRB搞砸了一段时间之后我无法理解它.
在模型中:
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
在控制器中:
@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')
可以找到ActiveRecord查询的文档:
http://guides.rubyonrails.org/active_record_querying.html#ordering
如果您希望在find_by_first_letter定义中实现该顺序,那么您可以简单地将.order()函数链接如下:
class Movie < ActiveRecord::Base validates_presence_of :title def self.find_by_first_letter(letter) where('title LIKE ?',"#{letter}%").order('title ASC') end end