0
0

Rails7でannotateのgemで自動でアノテーションを付与する

Last updated at Posted at 2024-08-04

やりたかったこと

モデルファイルにdbのマイグレーションをした際に自動でスキーマ情報を記載し、わざわざdbを確認しに行く手間を省きたい

こんな感じ
# == Schema Information
#
# Table name: boards
#
#  id          :bigint           not null, primary key
#  author_name :string(255)
#  body        :text(65535)
#  title       :string(255)
#  created_at  :datetime         not null
#  updated_at  :datetime         not null
#
class Board < ApplicationRecord
    validates :author_name, presence: true, length: { maximum:10 }
    validates :title, presence: true, length: { maximum:30 }
    validates :body, presence: true, length: { maximum:1000 }
end

問題点

準備としてGemfileに下記を記述し、bundle installを実行し

gem 'annotate'

以下のコマンドを実行すると動いてくれるらしいが実行してもモデルファイルに変化なし

bundle exec annotate

原因

以下の記事に書いてある通りrails6でke routes が廃止され、rails routes でルート一覧が出るようになった。
Gem の内部のコードで rake routes が使われているので、そこを書き換えると動くらしい。

がrails初心者おじさんは下手にgem管理配下のファイルを修正するのは抵抗がある。
そのため、なるべく現状維持のままいい感じに機能だけ使いたい

解決方法

auto_annotate_models.rakeというファイルを作成し、データベースの
マイグレーションが実行された タイミングでモデルのアノテーションを記載してくれた。
以下のコマンドでファイルを作成する。

rails g annotate:install

その後、マイグレーションを行うことでこのページのトップに記載したようなアノテーションが作成された

bundle exec rake db:migrate
models/board.rb
# == Schema Information
#
# Table name: boards
#
#  id          :bigint           not null, primary key
#  author_name :string(255)
#  body        :text(65535)
#  title       :string(255)
#  created_at  :datetime         not null
#  updated_at  :datetime         not null
#
class Board < ApplicationRecord
    validates :author_name, presence: true, length: { maximum:10 }
    validates :title, presence: true, length: { maximum:30 }
    validates :body, presence: true, length: { maximum:1000 }
end

注意点

公式のGithubを見ると最後のリリースが2022年2月だった。2024年8月現在更新は停止しているようだ。gemをインストールする場合は多くの人は開発用のgemとして定義すると思う。そのため、導入している製品などに影響はないと思うが使用するときはいつ使えなくなるかわからない覚悟が必要だ

Gemfile
group :development do
  gem 'annotate'
end

参考

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