LoginSignup
7
3

More than 3 years have passed since last update.

Rails6 のちょい足しな新機能を試す91(ActiveRecord annotate編)

Posted at

はじめに

Rails 6 に追加された新機能を試す第91段。 今回は、 ActiveRecord annotate 編です。
Rails 6 では、 ActiveRecord で、発行される SQL にコメントを含めることができるように annotate メソッドが追加されました。
ログに出力して解析したり、デバッグしたりするときに便利そうです。

Ruby 2.6.4, Rails 6.0.0 で確認しました。

$ rails --version
Rails 6.0.0

今回は、User の CRUD を作り、一覧ページを表示するとき、そこで実行される SQL がどのコントローラのどのアクションから呼ばれているのかわかるようにしてみます。

プロジェクトを作る

rails new rails_sandbox
cd rails_sandbox

User の CRUD を作る

name をもつ User の CRUD を作ります

bin/rails g scaffold User name

コントローラとアクションの名前を返すメソッドを定義する

full_action_name というプライベートメソッドを ApplicationController に追加します

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  private

  def full_action_name
    "#{self.class.name}##{action_name}"
  end
end

ApplicationRecord に scope を追加する

annotate を使った scope を1つ ApplicationRecord に追加します。

app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
  scope :called_from, ->(from) { annotate("called from #{from}") }
end

UserController#index を変更する

User.allUsersController#index から呼ばれていることがわかるように、修正します。

app/controllers/users_controller.rb
class UsersController < ApplicationController
  ...
  def index
    @users = User.all.called_from(full_action_name)
  end
  ...
end

実際に一覧ページを表示してコンソールを確認する

rails server を実行し、ブラウザから http://localhost:3000/users にアクセスし、コンソールを確認します。
SQL 文にコメント"called from UsersController#index" が含まれていることがわかります。

...
  User Load (0.4ms)  SELECT "users".* FROM "users" /* called from UsersController#index */
...

試したソース

試したソースは以下にあります。
https://github.com/suketa/rails_sandbox/tree/try091_activerecord_annotate

参考情報

7
3
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
7
3