Ruby3.1.4から3.2.2へ、Rails6.1から7.0へのバージョンアップと、
WebpackerからSprocketsに移行したので手順をメモしておきます。

Rails7.1にしなかったのでは、現段階でDevise Token Authが対応していなかった為です。
また、Webpackerは開発終了したので、rails new(デフォルト)で入るSprocketsに変更します。
WebpackerではNode.jsが必要でしたが、Sprocketsにすると不要になる。
Node.js v16(2023/09/11でサポートが終了している)じゃないと動かないけど、
Nuxt3はv18以降じゃないと動かないのが厄介でしたが、解消できます。

rails new(デフォルト)は、下記のように変更されています。
・webpacker -> sprockets-rails + importmap-rails
・turbolinks -> turbo-rails
・sass-rails -> sassc-rails

Rubyバージョンアップ(RVM)

序でに、Homebrewや使っているものもバージョンアップしました。
環境構築手順(Macの場合) -> README.md – Repos

普通にやるとエラーになったので、下記を参考にしました。
Error when installing openssl version 1.0 (MacOS Big Sur, Version 11.7.6. i7) · Issue #9 · rbenv/homebrew-tap · GitHub

% brew install openssl@3

※ターミナルを開き直して、
% openssl version
OpenSSL 3.1.4 24 Oct 2023 (Library: OpenSSL 3.1.4 24 Oct 2023)

% rvm install 3.2.2 --with-openssl-dir=$(brew --prefix openssl@3)
% rvm --default use 3.2.2

% ruby -v
ruby 3.2.2 (2023-03-30 revision e51014f9c0) [arm64-darwin22]

% rvm list
   ruby-3.1.4 [ arm64 ]
=* ruby-3.2.2 [ arm64 ]

.ruby-version

- ruby-3.1.4
+ ruby-3.2.2

Gemfile

- ruby '3.1.4'
+ ruby '3.2.2'
% bundle install

動作確認

% bin/webpack-dev-server
% rails s
% open http://localhost:3000/

% rspec
% rubocop
% brakeman

サーバー側: cannot load such file — psych (LoadError)

RVMでRubyをバージョンアップしようとしたら下記のエラーが出ました。

<internal:/home/railsapp/.rvm/src/ruby-3.2.2/lib/rubygems/core_ext/kernel_require.rb>:85:in
 `require': cannot load such file -- psych (LoadError)

Ruby 3.2.0 リリース

3rd パーティライブラリのソースコード同梱廃止
・libyaml や libffi のような 3rd パーティのライブラリのソースコードの同梱を廃止しました

libyaml-develをインストールすればOK

# yum install libyaml-devel

Railsバージョンアップ

Rails アップグレードガイド – Railsガイド

Gemfile

- gem 'rails', '~> 6.1'
-+ gem 'rails', '~> 7.1'
+ gem 'rails', '~> 7.0'

現時点で、Devise Token Authが7.1未満だったので、7.0にしました。

% bundle update
Because devise_token_auth >= 1.2.1 depends on rails >= 4.2.0, < 7.1
  and devise_token_auth >= 1.1.5, < 1.2.1 depends on rails >= 4.2.0, < 6.2,
  devise_token_auth >= 1.1.5 requires rails >= 4.2.0, < 7.1.
% bundle install
% bin/rails -v
Rails 7.0.8

bin/が不要になるようにローカルのRailsも更新しておきます。

% gem install -v 7.0.8 rails
% rails -v
Rails 7.0.8

アップデートタスク

設定が飛びますが、一旦、すべてYesで上書きして、後で、差分を確認して必要なのを戻します。

% rails app:update
% rubocop -a

不要なファイルを削除

rails 7.0では`config/initializers`配下のファイルが少なくなっている #Ruby - Qiita

config/initializersの下記を削除

application_controller_renderer.rb
backtrace_silencers.rb
cookies_serializer.rb
mime_types.rb
wrap_parameters.rb

Rails7.0設定移行・エラー修正

差分を確認して必要な設定を移行します。
環境により違うので参考までに私のを記載しておきます。

config/environments/development.rb

  ### START ###
  config.action_mailer.default_url_options = { host: Settings.base_domain }
  config.action_mailer.delivery_method = :letter_opener_web
  ### END ###

config/environments/production.rb

  ### START ###
  config.hosts << Settings.base_domain
  ### END ###

-  config.log_level = :info
  ### START ###
  # config.log_level = :info
  config.log_level = ENV['LOG_LEVEL'].present? ? ENV['LOG_LEVEL'].to_sym : :info
  ### END ###

  ### START ###
  config.action_mailer.default_url_options = { host: Settings.base_domain, protocol: 'https' }
  config.action_mailer.delivery_method = ENV['DELIVERY_METHOD'].present? ? ENV['DELIVERY_METHOD'].to_sym : :sendmail
  config.action_mailer.smtp_settings = ENV['SMTP_SETTINGS'].present? ? eval(ENV['SMTP_SETTINGS']) : nil
  ### END ###

config/environments/test.rb

  ### START ###
  config.action_mailer.default_url_options = { host: Settings.base_domain }
  ### END ###

config/initializers/content_security_policy.rb

Rails.application.configure do
  config.content_security_policy do |policy|
    policy.default_src :self, :https
    policy.font_src    :self, :https, :data
    policy.img_src     :self, :https, :data
    policy.object_src  :none
    # policy.script_src  :self, :https
    policy.script_src  :self, :https, :unsafe_inline
    # policy.style_src   :self, :https
    policy.style_src   :self, :https, :unsafe_inline
    # Specify URI for violation reports
    # policy.report_uri "/csp-violation-report-endpoint"
    # :nocov:
    policy.connect_src :self, :https, 'http://localhost:3035', 'ws://localhost:3035' if Rails.env.development?
    # :nocov:
  end

  # Generate session nonces for permitted importmap and inline scripts
  # config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s }
  # config.content_security_policy_nonce_directives = %w(script-src)

  # Report violations without enforcing the policy.
  # config.content_security_policy_report_only = true
end

config/initializers/cors.rb

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*',
             headers: :any,
             methods: %i[get post patch put delete options head],
             expose: %i[token-type uid client access-token expiry]
  end
end

config/initializers/new_framework_defaults_7_0.rb

-> 削除

config/application.rb

-    config.load_defaults 6.1
+    config.load_defaults 7.0
    ### START ###
    config.i18n.fallbacks = true
    config.i18n.default_locale = :ja
    config.time_zone = 'Tokyo'
    config.action_view.field_error_proc = proc { |html_tag, _instance| html_tag }
    config.active_job.queue_adapter = :delayed_job
    ### END ###

動作確認

現段階で、Gemのアップデート(bundle update)をしちゃうと、Railsの問題なのか他のGemの問題なのかの切り分けが難しくなるので、後で実施する事にします。

% rails db:migrate
% bin/webpack-dev-server
% rails s
% open http://localhost:3000/

% rspec

ActionView::Template::Error

      ActionView::Template::Error:
        Missing partial ./admin_users/shared/_error_messages

./ で指定できなくなったので、/ に変更

- render './
+ render '/
- json.partial! './
+ json.partial! '/
- json.partial!('./
+ json.partial!('/

Integer#to_s(:delimited) is deprecated.

DEPRECATION WARNING: Integer#to_s(:delimited) is deprecated. Please use Integer#to_fs(:delimited) instead.
- to_s(:
+ to_formatted_s(:

ActionController::Redirecting::UnsafeRedirectError

      Failure/Error: super

      ActionController::Redirecting::UnsafeRedirectError:
        Unsafe redirect to "http://front.localhost.test/?reset_password_token=0cfa8ab8-a2c7-467e-95c8-13a59e6ad46d",
         pass allow_other_host: true to redirect anyway.

外部にredirect_toしている箇所にallow_other_host: trueを追加してあげればOK

- return redirect_to Settings.confirmation_success_url_not if redirect_url.blank?
+ return redirect_to Settings.confirmation_success_url_not, allow_other_host: true if redirect_url.blank?

なのですが、Gemでredirect_toしている所には追加できないので、暫定でチェックを外しました。

config/application.rb

    # NOTE: Devise Token Authが対応していない為 -> ActionController::Redirecting::UnsafeRedirectError
    config.action_controller.raise_on_open_redirects = false

element matching "input[type=\"submit\"]", found 0.

       Minitest::Assertion:
         Expected at least 1 element matching "input[type=\"submit\"]", found 0.
         Expected 0 to be >= 1.
-        assert_select 'input[type=?]', 'submit'
+        assert_select 'button[type=?]', 'submit'

Gemバージョンアップ

rails newと比較して更新

% rails _7.0.8_ new rails708
% rails _7.0.8_ new rails708m -d mysql
% rails _7.0.8_ new rails708p -d postgresql

Gemfileを更新

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '3.2.2'

- # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
+ # Bundle edge Rails instead: gem 'rails', github: 'rails/rails', branch: 'main'
gem 'rails', '~> 7.0'

+ # The original asset pipeline for Rails [https://github.com/rails/sprockets-rails]
+ gem 'sprockets-rails'

# Use sqlite3 as the database for Active Record
# gem 'sqlite3', '~> 1.4'

# Use mysql as the database for Active Record
- gem 'mysql2', '~> 0.4.4'
+ gem 'mysql2', '~> 0.5'

# Use postgresql as the database for Active Record
# gem 'pg', '~> 1.1'

- # Use Puma as the app server
- gem 'puma', '~> 4.1'
+ # Use the Puma web server [https://github.com/puma/puma]
+ gem 'puma', '~> 5.0'

- # Use SCSS for stylesheets
- gem 'sass-rails', '>= 6'

- # Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
- gem 'webpacker', '~> 5.0'
+ # Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails]
+ gem 'importmap-rails'

- # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
- gem 'turbolinks', '~> 5'
+ # Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev]
+ gem 'turbo-rails'

+ # Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev]
+ gem 'stimulus-rails'

- # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
- gem 'jbuilder', '~> 2.7'
+ # Build JSON APIs with ease [https://github.com/rails/jbuilder]
+ gem 'jbuilder'

# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'

+ # Use Kredis to get higher-level data types in Redis [https://github.com/rails/kredis]
+ # gem 'kredis'

- # Use Active Model has_secure_password
+ # Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword]
# gem 'bcrypt', '~> 3.1.7'

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: %i[mingw mswin x64_mingw jruby]

# Reduces boot times through caching; required in config/boot.rb
- gem 'bootsnap', '>= 1.4.2', require: false
+ gem 'bootsnap', require: false

+ # Use Sass to process CSS
+ gem 'sassc-rails'

- # Use Active Storage variant
+ # Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images]
# gem 'image_processing', '~> 1.2'

group :development, :test do
-  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
-  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
+  # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem
+  gem 'debug', platforms: %i[mri mingw x64_mingw]

  # Use RSpec
-  gem 'rspec-rails', '>= 4.0.0' # NOTE: https://qiita.com/amatsukix/items/578f85cf4565ca2a797c
+  gem 'rspec-rails'
-  gem 'spring-commands-rspec'
+  # gem 'spring-commands-rspec'
-  gem 'factory_bot_rails'
+  gem 'factory_bot_rails', '< 6.3.0' # NOTE: rails s/rspec -> undefined method `config' for nil:NilClass
  # Use RuboCop
  gem 'rubocop'
  gem 'rubocop-rails'
  # Use Brakeman
  gem 'brakeman'
end
gem 'faker' # NOTE: テスト以外でも使えるように
- gem 'rexml' # NOTE: rails aborted! LoadError: cannot load such file -- rexml/document

group :development do
-  # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
-  gem 'web-console', '>= 3.3.0'
+  # Use console on exceptions pages [https://github.com/rails/web-console]
+  gem 'web-console'

-  # gem 'listen', '>= 3.0.5' # NOTE: LoadError: Could not load the 'listen' gem. Add `gem 'listen'` to the development group of your Gemfile

+  # Add speed badges [https://github.com/MiniProfiler/rack-mini-profiler]
+  # gem 'rack-mini-profiler'

-  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
-  gem 'spring'
+  # Speed up commands on slow machines / big apps [https://github.com/rails/spring]
+  # gem 'spring'
-  gem 'spring-watcher-listen', '>= 2.0.0'
  # Use YARD
  gem 'guard-yard'
  gem 'redcarpet'
  gem 'yard'
  # Use LetterOpenerWeb
-  # gem 'letter_opener_web' # NOTE: NameError: uninitialized constant LetterOpenerWeb
+  gem 'letter_opener_web'
  # Use Rails ERD
  gem 'rails-erd'
  # Use Bullet
  gem 'bullet'
  # Use Capistrano
-  gem 'capistrano', '>= 3.0'
+  gem 'capistrano'
  gem 'capistrano-rvm'
  gem 'capistrano-rails'
  gem 'capistrano-bundler'
  gem 'capistrano-yarn'
  gem 'capistrano3-unicorn'
end
- gem 'listen', '>= 3.0.5'
- gem 'letter_opener_web'

group :test do
-  # Adds support for Capybara system testing and selenium driver
-  gem 'capybara', '>= 2.15'
+  # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing]
+  gem 'capybara'
  gem 'selenium-webdriver'
-  # Easy installation and use of web drivers to run system tests with browsers
-  gem 'webdrivers'

  # Use SimpleCov
  gem 'simplecov'
  # Use Ruby Tests Profiling Toolbox
  gem 'test-prof'
  # Use WebMock
  gem 'webmock'
end

# Use Devise
gem 'devise'
gem 'devise-i18n'
gem 'email_validator'

# Use Devise Token Auth
gem 'devise_token_auth'
gem 'rack-cors'

# Use RailsAdmin
gem 'rails_admin'
gem 'rails_admin-i18n'

# Use PaperTrail
gem 'paper_trail'

# Use Config
gem 'config'

# Use kaminari
gem 'kaminari'
gem 'kaminari-i18n'

# Use CarrierWave/MiniMagick
gem 'carrierwave'
gem 'mini_magick'

# Use EnumHelp
gem 'enum_help'

# Use Unicorn
gem 'unicorn'

# Use Exception Notification
gem 'exception_notification'
gem 'slack-notifier'

# Use Delayed::Job
gem 'delayed_job_active_record'
gem 'daemons'

- # NOTE: [ruby 3.0.0 -> 3.1.4] rails s -> Psych::BadAlias: Unknown alias: male_first_name
- gem 'psych', '~> 3.1'
- 
- # NOTE: [ruby 3.0.0 -> 3.1.4] rspec -> LoadError: cannot load such file -- matrix, net/smtp
- gem 'matrix'
- gem 'net-smtp'
% bundle update

undefined method `config' for nil:NilClass (NoMethodError)

下記エラーになった為、factory_bot_railsのバージョンを6.3.0未満に下げています。

% rails s
/Users/xxxx/.rvm/gems/ruby-3.2.2/gems/railties-7.0.8/lib/rails.rb:47:in
 `configuration': undefined method `config' for nil:NilClass (NoMethodError)

      application.config
                 ^^^^^^^
	from /Users/xxxx/.rvm/gems/ruby-3.2.2/gems/factory_bot_rails-6.4.0/lib/factory_bot_rails/railtie.rb:25:in `block in '

% rspec 

An error occurred while loading ./spec/helpers/application_helper_spec.rb.
Failure/Error: require File.expand_path('../config/environment', __dir__)

NoMethodError:
  undefined method `config' for nil:NilClass
# /Users/xxxx/.rvm/gems/ruby-3.2.2/gems/railties-7.0.8/lib/rails.rb:47:in `configuration'
# /Users/xxxx/.rvm/gems/ruby-3.2.2/gems/factory_bot_rails-6.4.0/lib/factory_bot_rails/railtie.rb:25:in `block in '

差分を確認しながら、他のファイルを更新

rails newしたファイルを確認しながらコピペして更新して行きます。

数が多いので、一部のみ記載します。他は下記コミットを参照してください。
origin#557 Sprocketsに移行、Gemバージョンアップ

ImportMap関連

config/importmap.rb

# Pin npm packages by running ./bin/importmap

pin 'application', preload: true
pin '@hotwired/turbo-rails', to: 'turbo.min.js', preload: true
pin '@hotwired/stimulus', to: 'stimulus.min.js', preload: true
pin '@hotwired/stimulus-loading', to: 'stimulus-loading.js', preload: true
pin_all_from 'app/javascript/controllers', under: 'controllers'

app/javascript/application.js

// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails
import '@hotwired/turbo-rails'
import 'controllers'

app/javascript/controllers/application.js

import { Application } from '@hotwired/stimulus'

const application = Application.start()

// Configure Stimulus development experience
application.debug = false
window.Stimulus   = application

export { application }

app/javascript/controllers/index.js

// Import and register all your controllers from the importmap under controllers/*

import { application } from 'controllers/application'

// Eager load all controllers defined in the import map under controllers/**/*_controller
import { eagerLoadControllersFrom } from '@hotwired/stimulus-loading'
eagerLoadControllersFrom('controllers', application)

// Lazy load controllers as they appear in the DOM (remember not to preload controllers in import map!)
// import { lazyLoadControllersFrom } from '@hotwired/stimulus-loading'
// lazyLoadControllersFrom('controllers', application)

app/javascripts/controllers/xxx_controller.jsを作れば自動で読み込まれると。
ただ、記法はStimulusになるので、単にリネームしただけだと、動くけど下記エラーが出る。

TypeError: Cannot read properties of undefined (reading 'shouldLoad')

下記を入れればエラーは出なくなるけど、動かなくなる。

export default {}

GitHub - hotwired/stimulus-rails: Use Stimulus in your Ruby on Rails app

app/views/layouts/application.html.erb

<!DOCTYPE html>
<html lang="ja">
  <head>
-    <meta charset="UTF-8" />
-    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
-    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <title><%= content_for?(:html_title) ? yield(:html_title) + ' - ' : '' %><%= "#{t('app_name')}#{Settings.env_name}" %></title>
+    <meta name="viewport" content="width=device-width,initial-scale=1">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" />
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" />
    <link rel="stylesheet" href="<%= config.asset_host %>/css/mdb.min.css?v3.1.0" />
-    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
+    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbo-track': 'reload' %>
<% if Settings.debug %>
    <meta name="debug" content="true">
<% end %>
-    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
+    <%= javascript_importmap_tags %>

jQuery追加(必要な場合)

% bin/importmap pin jquery

config/importmap.rb に下記が追加されます。

pin 'jquery', to: 'https://ga.jspm.io/npm:jquery@3.7.1/dist/jquery.js'

実装を移行(layouts)

序でに今まで全ページで無駄に呼んでいたJSを、使うlayoutsだけに変更します。

app/javascript/packs/application.js -> app/javascript/controllers/left_menu.js

- // This file is automatically compiled by Webpack, along with any other files
- // present in this directory. You're encouraged to place your actual application logic in
- // a relevant structure within app/javascript and only use these pack files to reference
- // that code so it'll be compiled.
-
- require('@rails/ujs').start()
- require('turbolinks').start()
- require('@rails/activestorage').start()
- require('channels')
- require('jquery')
-
- // Uncomment to copy all static images under ../images to the output folder and reference
- // them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
- // or the `imagePath` JavaScript helper below.
- //
- // const images = require.context('../images', true)
- // const imagePath = (name) => images(name, true)

+ import jquery from 'jquery'
+ window.$ = jquery

const debug = $("meta[name='debug']").attr('content') === 'true'
let leftMenuDisplay = null

- $(document).on('turbolinks:load', function(){
+ $(document).on('turbo:load', function(){
-    if (debug) console.log('== turbolinks:load', leftMenuDisplay)
+    if (debug) console.log('== turbo:load', leftMenuDisplay)

app/views/layouts/application.html.erb

    <%= javascript_importmap_tags %>
+    <%= javascript_import_module_tag 'controllers/left_menu' %>

app/javascript/controllersにファイルを置くだけで、<script type="importmap"の中に入り、javascript_import_module_tagで呼び出せます。
controllers/始まりなのが少し気になりますが、config/importmap.rbに毎回追加するのも微妙だし、layouts/始まりで自動読み込みされるようにするのも手間でレールから外れそうだし、そもそも、あまり数が増えないので、今の所はこれで妥協。

RailsAdminをwebpackerからsprocketsに変更

config/initializers/rails_admin.rb

-  config.asset_source = :webpacker
+  config.asset_source = :sprockets

下記が不要になったので削除します。

app/javascript/packs/rails_admin.js
app/javascript/stylesheets/rails_admin.scss

ボタンがクリックできない(turboに変更)

actionview - Rails 7: local (non-XHR) request with a form_with form - Stack Overflow

turbolinksからturboに変わった為、
local: truedata: { turbo: false } に変更する必要があります。

app/views/users/registrations/_new_user.html.erb

- <%= form_with(<省略>, local: true) do |form| %>
- <%= form_with(<省略>, data: { turbo: false }) do |form| %>

CSP(コンテンツセキュリティポリシー)

登録や変更ボタンをクリックするとエラーになるので、script_srcに:blobを追加します。

Refused to execute inline event handler because it violates the following
 Content Security Policy directive: "script-src 'self' https: 'unsafe-inline'
  'nonce-607e9c9008282476644e0115c597a741'".
 Note that 'unsafe-inline' is ignored
  if either a hash or nonce value is present in the source list.

config/initializers/content_security_policy.rb

Rails.application.configure do
  config.content_security_policy do |policy|
    policy.default_src :self, :https
    policy.font_src    :self, :https, :data
    policy.img_src     :self, :https, :data
    policy.object_src  :none
    # policy.script_src  :self, :https
-    policy.script_src  :self, :https, :unsafe_inline
+    policy.script_src  :self, :https, :unsafe_inline, :blob
    # policy.style_src   :self, :https
    policy.style_src   :self, :https, :unsafe_inline
    # Specify URI for violation reports
    # policy.report_uri "/csp-violation-report-endpoint"
-    # :nocov:
-    policy.connect_src :self, :https, 'http://localhost:3035', 'ws://localhost:3035' if Rails.env.development?
-    # :nocov:
  end

  # Generate session nonces for permitted importmap and inline scripts
  # config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s }
  # config.content_security_policy_nonce_directives = %w(script-src)

  # Report violations without enforcing the policy.
  # config.content_security_policy_report_only = true
end

Webpackerが不要になった、ws(WebSocket)は未使用なので、削除しちゃいます。

Webpacker等の削除

下記が不要になったので削除します。

bin/webpack
bin/webpack-dev-server
bin/yarn
config/webpack/development.js
config/webpack/environment.js
config/webpack/production.js
config/webpack/test.js
config/webpacker.yml
babel.config.js
package.json
yarn.lock

下記も削除しています。

bin/spring
config/spring.rb
.browserslistrc
postcss.config.js
public/packs
public/packs-test

Capfile locked at ~> 3.17.1, but 3.18.0 is loaded

% cap production deploy
Capfile locked at ~> 3.17.1, but 3.18.0 is loaded

config/deploy.rb

- lock '~> 3.17.1'
+ lock '~> 3.18.0'

Sprockets::ArgumentError: link_tree argument must be a directory

% cap production deploy
00:27 deploy:assets:precompile
      01 ~/.rvm/bin/rvm ruby-3.2.2 do bundle exec rake assets:precompile
      01 rake aborted!
      01 Sprockets::ArgumentError: link_tree argument must be a directory (Sprockets::ArgumentError)
      01 /home/railsapp/app/releases/20231201004630/app/assets/config/manifest.js:4

app/assets/config/manifest.js

//= link_tree ../../../vendor/javascript .js

サーバー側

$ cd app/current
$ ll vendor
lrwxrwxrwx 1 railsapp nginx 32 12月  1 15:08 vendor -> /home/railsapp/app/shared/vendor

$ ll vendor/
合計 0

シンボリックリンクになっていて、javascriptディレクトリがないのが原因。

$ mkdir vendor/javascript

下記の設定にvendorも含まれている為。

config/deploy.rb

append :linked_dirs, "log", "tmp/pids", "tmp/cache", "tmp/sockets",
                     "tmp/webpacker", "public/system", "vendor", "storage"

undefined local variable or method 'javascript_importmap_tags'

上記の対応で、下記を削除したからなのか、

app/assets/config/manifest.js

//= link_tree ../../../vendor/javascript .js

デプロイは成功しましたが、アクセスすると500エラーになりました。
戻して、javascriptディレクトリ作成したら、何故か解消しました。

An ActionView::Template::Error occurred while GET </> was processed by top#index
Exception
undefined local variable or method 'javascript_importmap_tags' for #

Dockerバージョンアップ

Dockerfile

Rubyのバージョン変更と、Node.jsとYarnが不要になったので削除。

- FROM ruby:3.1.4-alpine
+ FROM ruby:3.2.2-alpine

- # NOTE: Error: error:0308010C:digital envelope routines::unsupported
- ENV NODE_OPTIONS='--openssl-legacy-provider'

- COPY package.json yarn.lock ./
- RUN yarn install && yarn cache clean

compose.yml

序でにMySQLとPostgreSQLのバージョン変更と、Webpackerが不要になったので削除。

services:
  db:
    platform: linux/x86_64 # Tips: mysql -> ERROR: no matching manifest for linux/arm64/v8 in the manifest list entries
-    image: mysql:8.0.33 # https://hub.docker.com/_/mysql
+    image: mysql:8.2.0 # https://hub.docker.com/_/mysql

  pg:
-    image: postgres:15.3-alpine # https://hub.docker.com/_/postgres
+    image: postgres:16.1-alpine # https://hub.docker.com/_/postgres

  app:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/workdir
      - /workdir/node_modules
    ports:
      - 3000:3000
    depends_on:
      - db
      - pg
-    environment:
-      WEBPACKER_DEV_SERVER_HOST: webpack
-  webpack:
-    build: .
-    command: bin/webpack-dev-server --host 0.0.0.0 --port 3035
-    volumes:
-      - .:/workdir
-      - /workdir/node_modules
-    ports:
-      - 3035:3035
-    environment:
-      WEBPACKER_DEV_SERVER_HOST: 0.0.0.0

動作確認

% docker compose up --build
% docker compose run app rails db:create
% docker compose run app rails db:migrate
% docker compose run app rails db:seed

% open http://localhost:3000

今回のコミット内容

yarn installやbin/webpack-dev-server、Node.jsが不要になりました。springも。

origin#557 Ruby3.2.2にバージョンアップ
origin#557 Rails7.0にバージョンアップ
origin#557 Rails7.0設定移行・エラー修正
origin#557 Sprocketsに移行、Gemバージョンアップ
origin#557 Dockerバージョンアップ、リファクタ

origin#557 Rails7.0エラー修正

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です