使用SQL检索一组记录,然后使用Rails对它们进行排序
使用Rails 3.2和MariaDB。 我的表有500,000行。 在通常的查询中,我们将在其中添加order
子句,如下所示:
# takes 4000ms to load, returns 100 records @shops = Shop.where(:shop_type => 'fashion').order('overall_rating DESC')
如果我们删除order
,则加载时间会大大减少:
# takes 20ms to load, returns 100 records @shops = Shop.where(:shop_type => 'fashion')
是否可以首先检索@shops
100记录,然后使用Rails通过overall_rating DESC
对它们进行overall_rating DESC
而不涉及SQL? 或者,将查询分为两部分:首先检索100条记录,然后订购该组记录。 这可以大大提高性能。
是的,排序集合是Ruby的Enumerable mixin的一部分。
@shops = Shop.where(:shop_type => 'fashion') @shops.sort! { |a,b| b.overall_rating <=> a.overall_rating }
- Ruby – Rails – SQL查询 – 在搜索词中重新排序单词
- Rails-MySQL错误 – 未初始化的常量MysqlCompat :: MysqlRes
- 在运行时连接到ruby中的两个不同的数据库
- utf8数据在mysql中看起来很好,但在rails中被破坏了
- 无法在OS X上安装mysql gem
- Rails应用程序错误 – ActiveRecord :: PendingMigrationError正在等待迁移; 运行’rake db:migrate RAILS_ENV = development’来解决此问题
- 使用rake db:migrate命令和mysql在Rails中创建表的PRIMARY KEY问题
- Rails 3有mysql问题
- 在Mac OS x Lion上安装mysql2 gem