如何在Rails中按字母顺序排序电影?

12
如果您访问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])

http://guides.rubyonrails.org/active_record_querying.html#ordering - Alistair A. Israel
就像他在字母中存储电影一样... a = ['蚂蚁人生','另一个'],b = ['锅炉房'] - 这就是让我困惑的地方。 - Sonny Black
要求提供代码的问题必须展示对问题的基本理解。请包括尝试过的解决方案,为什么它们不起作用以及预期结果。另请参阅:Stack Overflow问题清单 - the Tin Man
2个回答

25
# 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

3
我不理解为什么你不使用查询链接:
Movie.where('title LIKE ?', "a%").order(:title)

但更好的方法是,像Michael Lynch说的那样创建一个范围,这将增加您的代码可重用性。

实际上,您的代码正在发出弃用警告。您必须在Rails服务器终端窗口中进行检查。虽然它可以工作,但让它不受检查并不是一个好主意。

弃用警告:调用#find(:all)已弃用。请直接调用#all。您还使用了查找器选项。这些也已弃用。请构建一个范围,而不是使用查找器选项。(在(irb):1处调用)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接