加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何在Rails中按字母顺序对电影进行排序?

发布时间:2020-12-17 04:25:21 所属栏目:百科 来源:网络整理
导读:如果你访问 http://ccvideofinder.heroku.com/,这是我所指的一个很好的例子. 如何在Rails中完成?我在考虑使用case / when语句但是在与IRB搞砸了一段时间之后我无法理解它. 在模型中: class Movies ActiveRecord::Base validates_presence_of :title def se
如果你访问 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读