2026年11月30日月曜日

Ruby and Rails の、アプリを、ブラッシュアップ

ZIP

この、アプリの、バグを修正して、ログイン、新規ユーザー登録、セッション管理などの、機能を、追加する、方法などを、雑学や業界話を、交えながら、解説してください、

コードとログを読みました。先にお断りすると、この環境には Ruby が入っておらず、実際に起動してのテストはできていません。以下は静的に読んで、development.log のエラー履歴と突き合わせた結果です。


第1部:バグ修正

重大なものから順に並べます。

1. Gemfile が「二重のアセットパイプライン」になっている

ログに

link_tree argument must be a directory
が6回出ています。これは Sprockets のエラーです。この Gemfile は propshaft を使っていますが、sassc-rails や bootstrap gem が Sprockets を引き込んでしまい、2つのパイプラインが衝突しています。
ruby
# 削除する
gem 'sassc-rails'
gem 'bootstrap', '~> 5.3'
gem 'font-awesome-sass', '~> 6.4.0'
gem "kaminari-bootstrap", "~> 3.0"
gem 'pagy'          # kaminari と二重
gem 'kaminari'      # 2回書かれている(1つ残す)

# コメントを外す(認証で必須)
gem "bcrypt", "~> 3.1.7"

Bootstrap は layout で CDN から読んでいるので gem は不要です。Tailwind も入っているので、CSS フレームワークが2つ同居しています。どちらかに統一すると楽になります。

豆知識: Rails 7 以降、アセット周りは Sprockets → Propshaft、Webpacker → importmap と、短期間で世代交代しました。ネット上の古い記事を混ぜてコピペすると、こうした「新旧混在」が起きやすくなります。

2. 古いバックアップファイルが本番起動を壊す

app/ 配下に dashboard_controller01.rb、dashboard_controlle02r.rb、transactions_controller02.rb などがあります。Rails のオートローダー Zeitwerk は「ファイル名 = クラス名」を前提にしているので、eager_load = true の本番では起動時に Zeitwerk::NameError になります。ログの uninitialized constant HomeController も同じ系統の問題です。

次のファイルは削除してください。

  • app/controllers/*01.rb、*02.rb、dashboard_controlle02r.rb
  • app/views/**/*01.erb、*02.erb、index.blade.erb、about.html~.erb
  • app/views/layouts/application01/02.html.erb、app/views/posts/
  • config/routes02.rb、db/seeds01.rb、db/seeds02.rb
  • app/assets/stylesheets/ の application.scss、application02.css、application_css.css など

バックアップは Git に任せるのが正解です。.git はもうあるので、git commit すれば消しても戻せます。

あわせて app/controllers/concerns/cacheable.rb も直します。置き場所が違い、さらに中で class Transaction を再オープンしています。

ruby
# app/models/concerns/cacheable.rb  ← 場所を移動
module Cacheable
  extend ActiveSupport::Concern
  class_methods do
    def cached_monthly_summary(year, month)
      Rails.cache.fetch("monthly_summary_#{year}_#{month}", expires_in: 1.hour) { monthly_summary(year, month) }
    end
  end
end
# 下の class Transaction ... end は削除。Transaction 側で include Cacheable する

3. BudgetGoal の関連付けが壊れている(予算機能が動かない根本原因)

テーブルには category_id があるのに、モデルが has_many :category(単数形)になっています。ログの undefined method 'categories' for BudgetGoal はこれです。

ruby
class BudgetGoal < ApplicationRecord
  belongs_to :category          # has_many :category → これに

  validates :monthly_limit, presence: true, numericality: { greater_than: 0 }
  validates :current_month, :current_year, presence: true

  def current_spending
    range = Date.new(current_year, current_month).all_month
    category.transactions.expense.where(transaction_date: range).sum(:amount)
  end
end

class Category < ApplicationRecord
  has_many :budget_goals, dependent: :destroy   # 単数形の has_many :budget_goal は削除(重複もある)
  has_many :transactions, dependent: :destroy
end

BudgetGoalsController の permit も、実在しないカラム(name、target_amount、deadline)を許可しています。フォームも monthly_target や auto_update といった存在しない項目を送っています。

ruby
def create
  @budget_goal = BudgetGoal.new(budget_goal_params)
  if @budget_goal.save
    redirect_to budget_goals_path, notice: "予算を登録しました"
  else
    render :new, status: :unprocessable_entity   # ← Turbo では 422 が必須
  end
end

private

def budget_goal_params
  params.require(:budget_goal).permit(:category_id, :monthly_limit, :current_month,
                                      :current_year, :priority, :start_date, :end_date)
end

フォーム側は

form.collection_select :category_id, Category.order(:name), :id, :name
と form.number_field :monthly_limit に合わせます。

さらにスキーマにも罠があります。budget_goals.year が NOT NULL かつ UNIQUE なので、フォームが year を送らない限り保存に失敗します。送ったとしても「全カテゴリ合わせて年に1件」しか登録できません。

ruby
class FixBudgetGoalsIndexes < ActiveRecord::Migration[8.0]
  def change
    remove_index :budget_goals, :year
    change_column_null :budget_goals, :year, true
    add_index :budget_goals, [:category_id, :current_year, :current_month],
              unique: true, name: "idx_budget_goals_category_period"
  end
end

4. Turbo で「失敗したフォームが無反応」になる

render :new に status: :unprocessable_entity が無いと、Rails 7 以降の Turbo はレスポンスを描画しません。CategoriesController#update には :unprocessable_entry という typo もあり、更新バリデーションに失敗した瞬間に例外になります。

ruby
render :edit, status: :unprocessable_entity

豆知識: 実は Rack 3.1 以降、:unprocessable_entity は :unprocessable_content(RFC 9110 の新名称)へ改名が進んでいて、新しめの環境では非推奨警告が出ることがあります。HTTP 422 の名前は、WebDAV 由来の古い呼び名から正式名称に移行中です。

5. 月次レポートのバグ(ログの undefined method 'where' for nil)

  • コントローラは ローカル変数 transactions に代入していますが、ビューは @transactions を使っています(nil になる)。
  • グラフが「収入」カードの中にあるのに、中身は支出を集計しています。
  • 「前月」リンクが1月で month: 0、「次月」が12月で month: 13 になります。
  • annual アクションのビューが存在しません。ルートにある summary アクションも未実装です。
ruby
def monthly
  year  = params[:year].presence&.to_i  || Date.current.year
  month = (params[:month].presence&.to_i || Date.current.month).clamp(1, 12)
  @date = Date.new(year, month, 1)

  @transactions = Transaction.for_month(year, month).includes(:category)
  @summary = Transaction.monthly_summary(year, month)
  @expense_by_category = @transactions.expense.joins(:category).group("categories.name").sum(:amount).sort_by { -_2 }
  @income_by_category  = @transactions.income.joins(:category).group("categories.name").sum(:amount).sort_by { -_2 }
end
erb
<% prev_d, next_d = @date.prev_month, @date.next_month %>
<%= link_to "← 前月", reports_monthly_path(year: prev_d.year, month: prev_d.month) %>
<%= link_to "次月 →", reports_monthly_path(year: next_d.year, month: next_d.month) %>

Date#prev_month が年またぎを全部処理してくれるので、自前の三項演算子は不要です。

6. 取引一覧の合計が「そのページ分だけ」になる

.page(...).per(20) したあとに @transactions.income.sum しているので、合計は表示中の20件分です。絞り込み → 合計 → ページ分割の順にします。

ruby
scope = Transaction.includes(:category).recent
scope = scope.where(category_id: params[:category_id]) if params[:category_id].present?
scope = scope.where(transaction_type: params[:transaction_type]) if params[:transaction_type].present?
if params[:start_date].present? && params[:end_date].present?
  scope = scope.where(transaction_date: Date.parse(params[:start_date])..Date.parse(params[:end_date]))
end
@total_income  = scope.income.sum(:amount)
@total_expense = scope.expense.sum(:amount)
@transactions  = scope.page(params[:page]).per(20)

Date.parse は不正な日付で例外になるので、rescue Date::Error で囲むと安全です。Transaction の amount も numericality: { greater_than: 0 } にしておきましょう(収支は transaction_type で表現しているので、負の金額は不要です)。

7. マイグレーションが「後から書き換えられている」

create_budget_goals に priority と current_amount が直接入っているのに、後続の add_current_amount_to_budget_goal は存在チェックなしで add_column しています。新しい環境で db:migrate すると duplicate column で落ちます(手元の DB では動いているので気づきにくいです)。

ruby
add_column :budget_goals, :current_amount, :decimal, precision: 10, scale: 2, default: 0.0, null: false \
  unless column_exists?(:budget_goals, :current_amount)

豆知識: 公開済みのマイグレーションは書き換えず、「新しいマイグレーションで直す」のが業界の鉄則です。Rails のスキーマ管理は「schema_migrations に記録された適用済みバージョン」が正なので、過去ファイルを編集すると環境ごとに状態がズレます。

8. その他の小物

  • application.rb の PRAGMA: after_initialize で DB に接続しているため、DB 未作成の状態(db:create、assets:precompile)で落ちます。Rails 7.1 以降の SQLite アダプタは WAL や synchronous=NORMAL を標準で設定するので、丸ごと不要です。
  • config.cache_store = :solid_cache_store と queue_adapter = :solid_queue: application.rb に書くと開発環境にも効きますが、開発用のキャッシュ DB は定義されていません。production.rb に既にあるので、application.rb からは消します。
  • importmap: chart.min.js を ESM として読み込んでいますが、Chart.js v4 の配布物に chart.min.js が存在するかは怪しく、グローバルの Chart も期待通りに生えません。Chartkick の gem には importmap 用のファイルが同梱されています。
ruby
# config/importmap.rb(CDN の pin 2行と置き換え)
pin "chartkick", to: "chartkick.js"
pin "Chart.bundle", to: "Chart.bundle.js"
js
// app/javascript/application.js(DOMContentLoaded 周りは全部不要)
import "@hotwired/turbo-rails"
import "controllers"
import "chartkick"
import "Chart.bundle"
  • routes.rb: categories と budget_goals が2回ずつ定義されています。
    resources :budget_goals do resources :categories, controller: 'budget_goals' end
    というネストは、BudgetGoalsController に別リソースを混ぜていて、params[:budget_goal_id] という苦肉の分岐の原因です。ネストごと削除しましょう。
  • /sw.js: application#service_worker が未定義で 500 になります。Rails 8 標準の PWA ルート(コメントアウトされている rails/pwa の2行)を使うほうが簡単です。manifest アクションが ApplicationController の public メソッドなのも、全コントローラから見えてしまうので避けたいところです。
  • Api::DashboardController は 250000 などの固定値を返しています。本物にするか、使っていないなら削除してください。
  • Category.income_categories は「給与」などの名前をハードコードして収入かどうかを判定しています。名前を変えた瞬間に壊れるので、category_type に income / expense を持たせるのが定石です。

第2部:ログイン・新規登録・セッション管理

方針:Devise ではなく Rails 8 標準ジェネレータ

Rails 8.0 から認証ジェネレータが標準で入りました。

豆知識: それまでの Rails には「公式の認証」がなく、2009年に José Valim が作った Devise が10年以上デファクトでした。便利な反面「魔法が多くて中身が追いにくい」という声も根強く、Rails 8 のジェネレータはコードを自分のアプリに生成して見えるようにする方針です。ライブラリとして隠さず、あなたのコードとして置いてくれます。ブラックボックスにしないこの流れは、学習用にも向いています。

bash
# Gemfile で bcrypt を有効化してから
bundle install
bin/rails generate authentication
bin/rails db:migrate

User(email_address、password_digest)、Session(ip_address、user_agent)、Current、Authentication concern、SessionsController、パスワードリセット一式(PasswordsController、メーラー)が生成されます。ApplicationController に include Authentication が入り、デフォルトで全ページがログイン必須になります。公開したいページだけ allow_unauthenticated_access で開ける、「閉じるのが標準」の設計です。

豆知識: パスワードのハッシュ化に使う bcrypt は、1999年に Provos と Mazières が発表した方式で、わざと遅く、しかもコスト値を上げられるのが特徴です。25年経った今も現役なのは、「ハードウェアが速くなっても、設定を上げれば追従できる」からです。**「暗号は自作するな」**は業界の格言で、has_secure_password に任せるのが正解です。

新規登録(ジェネレータには含まれません)

登録フローはアプリごとに違いすぎるため、標準では意図的に省かれています。自作します。

ruby
# config/routes.rb
resource :registration, only: %i[new create]
ruby
# app/models/user.rb(ジェネレータ生成物に追記)
class User < ApplicationRecord
  has_secure_password
  has_many :sessions, dependent: :destroy
  has_many :categories,   dependent: :destroy
  has_many :transactions, dependent: :destroy

  normalizes :email_address, with: ->(e) { e.strip.downcase }
  validates :email_address, presence: true, uniqueness: true,
                            format: { with: URI::MailTo::EMAIL_REGEXP }
  validates :password, length: { minimum: 12 }, allow_nil: true
end
ruby
# app/controllers/registrations_controller.rb
class RegistrationsController < ApplicationController
  allow_unauthenticated_access only: %i[new create]
  rate_limit to: 5, within: 10.minutes, only: :create,
             with: -> { redirect_to new_registration_path, alert: "しばらく待ってから再度お試しください" }

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      start_new_session_for @user          # 生成済みの concern のメソッド
      redirect_to root_path, notice: "登録しました"
    else
      render :new, status: :unprocessable_entity
    end
  end

  private

  def user_params
    params.require(:user).permit(:email_address, :password, :password_confirmation)
  end
end

豆知識: rate_limit も Rails 8.0 の新機能です。以前は rack-attack という gem で作るのが定番でした。ログインや登録はボット(クレデンシャルスタッフィング)の的になるので、回数制限は入れておきたいところです。

ログイン側では、ジェネレータが User.authenticate_by を使っています。これは「ユーザーが存在しない場合でも同じ時間をかけてハッシュ比較する」タイミング攻撃対策済みのメソッド(Rails 7.1 で追加)なので、find_by と authenticate を自前で組み合わせないでください。

セッション管理を強化する

ジェネレータの Cookie は signed.permanent(約20年)で、サーバー側の sessions テーブルに有効期限もありません。ここを締めます。

① 有効期限(30日の無操作で失効)

ruby
# app/controllers/concerns/authentication.rb の find_session_by_cookie を変更
def find_session_by_cookie
  return unless (id = cookies.signed[:session_id])
  Session.where(updated_at: 30.days.ago..).find_by(id: id)&.tap do |s|
    s.touch if s.updated_at < 1.hour.ago      # 使うたびに延長(書き込みは1時間に1回まで)
  end
end

② 古いセッションの掃除: このプロジェクトには Solid Queue の config/recurring.yml が既にあるので、定期ジョブを足せます。

ruby
# app/jobs/prune_sessions_job.rb
class PruneSessionsJob < ApplicationJob
  def perform = Session.where(updated_at: ...30.days.ago).delete_all
end
yaml
# config/recurring.yml(production: の下)
prune_sessions:
  class: PruneSessionsJob
  schedule: every day at 4am

③ ログイン中の端末一覧と、他端末のログアウト: セッションが DB に載っているのがジェネレータ方式の強みです。JWT 方式だとできない「サーバー側から強制ログアウト」が簡単にできます。

ruby
# routes: resources :devices, only: %i[index destroy]
class DevicesController < ApplicationController
  def index
    @sessions = Current.user.sessions.order(updated_at: :desc)   # ip_address / user_agent を表示
  end

  def destroy
    Current.user.sessions.where.not(id: Current.session.id).find(params[:id]).destroy
    redirect_to devices_path, notice: "ログアウトしました"
  end
end

④ パスワード変更・リセット時は全セッションを破棄: パスワードリセット完了時に @user.sessions.destroy_all が入っているか、生成された PasswordsController#update を確認してください。無ければ追加です。

豆知識: Rails のデフォルトのセッションは、Cookie に暗号化したデータを丸ごと入れる「CookieStore」です(Rails 4 から暗号化)。サーバーに何も持たないので楽ですが、「あとから取り消す」ことができません。取り消せることを重視する金融・決済系では、DB セッション方式が選ばれることが多いです。

最重要:データをユーザーごとに分離する

家計簿は他人に見えたら致命的なデータです。ログインを付けても、全員が同じ Transaction.all を見ていては意味がありません。

豆知識: OWASP Top 10(2021)の第1位は Broken Access Control(アクセス制御の不備) です。典型例が Transaction.find(params[:id])。URL の ID を書き換えるだけで他人のデータが見える状態で、IDOR と呼ばれます。日本でも、家計簿・資産管理アプリは銀行口座と連携する性質上、2018年施行の改正銀行法で「電子決済等代行業」の登録制になりました。お金のデータを扱うサービスには、それだけ厳しい目が向けられています。

手順1: user_id を追加(まず NULL 許可で)

ruby
class AddUserToOwnedTables < ActiveRecord::Migration[8.0]
  def change
    %i[categories transactions budget_goals].each do |t|
      add_reference t, :user, null: true, foreign_key: true
    end
  end
end

手順2: 既存データを自分のユーザーに紐付ける(rails console)

ruby
owner = User.create!(email_address: "you@example.com", password: "十分に長いパスワード", password_confirmation: "十分に長いパスワード")
[Category, Transaction, BudgetGoal].each { |m| m.update_all(user_id: owner.id) }

手順3: null: false にして、モデルとコントローラを直す

ruby
# 別マイグレーションで change_column_null :categories, :user_id, false  (他2表も)

class Transaction < ApplicationRecord
  belongs_to :user
  belongs_to :category
  validate :category_must_be_own

  private

  def category_must_be_own
    errors.add(:category, "が不正です") if category && category.user_id != user_id
  end
end

class Category < ApplicationRecord
  belongs_to :user
  validates :name, uniqueness: { scope: :user_id }    # 全員で名前が被れなくなるのを防ぐ
end
ruby
# コントローラ側: Transaction.xxx / Category.xxx / BudgetGoal.xxx を、すべて Current.user. 経由に
@transactions = Current.user.transactions.includes(:category).recent
def set_transaction = @transaction = Current.user.transactions.find(params[:id])   # 他人のIDなら 404
@transaction = Current.user.transactions.new(transaction_params)
@categories  = Current.user.categories.order(:name)
Current.user.transactions.monthly_summary(year, month)   # クラスメソッドも関連経由なら絞り込みが効く

default_scope で Current.user を自動適用する流儀もありますが、バックグラウンドジョブやコンソールで漏れやすく、「魔法で守る」より「明示的に書く」方を推します。SaaS 界隈では、行レベル(user_id 列)、スキーマ分離(Apartment gem)、DB 分離とマルチテナントの方式論争が長く続いていて、PostgreSQL の Row Level Security を保険に重ねる構成も人気です。個人向け家計簿なら、user_id 方式で十分です。

最後に「他人のデータは見えない」ことをテストで固定しておくと安心です。

ruby
test "他人の取引は 404" do
  sign_in_as users(:alice)
  get transaction_path(transactions(:bob_lunch))
  assert_response :not_found
end

第3部:セキュリティ上の注意

アップロードされた zip に config/master.key が入っていました。.gitignore には入っているので Git には載りませんが、zip にまとめると一緒に梱包されてしまいます。このキーで credentials.yml.enc が復号できるので、他人に渡す zip には含めず、すでに共有してしまった場合は、credentials に API キー等があればローテーションしてください。


進め方の提案

作業順は ①Gemfile・不要ファイルの整理 → ②モデル・コントローラのバグ修正 → ③認証追加 → ④user_id 分離 がおすすめです。①と②で「まず普通に動く家計簿」にしてから認証を載せると、問題の切り分けがしやすくなります。

ご希望なら、①〜④を反映した修正済みプロジェクトを zip でお渡しします。ただしこの環境では Ruby が動かないため未実行になります。手元で bin/rails zeitwerk:check と bin/rails test を回していただく前提になりますが、それでよろしいですか?


0 件のコメント: