LoginSignup
9
6

More than 5 years have passed since last update.

ActiveRecordでindexを指定する

Posted at

何したいの

indexを絶対に使って欲しい。

テーブル

users.sql
CREATE TABLE `users` (
  `id` bigint(20) unsigned NOT NULL COMMENT 'ユーザーID',
  `name` varchar(16) CHARACTER SET utf8 NOT NULL COMMENT 'ユーザー名',
  `created_at` datetime NOT NULL COMMENT '作成日時',
  `updated_at` datetime NOT NULL COMMENT '更新日時',
  PRIMARY KEY (`id`),
  KEY `index_users_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

モデル

user.rb
class Users < ActiveRecord::Base
  scope :use_index, ->(index) { from("#{self.table_name} USE INDEX(#{index})") }
end

実装

call.rb
User.use_index('index_users_name').all

fromを使うことでindexを指定出来る。
普通なら指定せずともDBが上手くやってくれる気がするのだけど、強制したい場合があったのでメモ。

参考資料

9
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
6