LoginSignup
18
9

More than 5 years have passed since last update.

[Rails] model名が原因でエラーになる場合の対処方法

Posted at

概要

bundle exec rails g model xxx を実行すると以下のエラーが発生する。
このエラーを解消するための方法そして原因について書き記すものである。

The name 'xxx' is either already used in your application or reserved by Ruby on Rails. Please choose an alternative and run this generator again.

前提

  • Ruby 2.5.1
  • Rails 5.2
  • RailsアプリケーションをHogeで作成(bundle exec rails new hoge)
  • HogeアプリケーションをHogeCoreにアプリケーションを変更

エラー

$ bundle exec rails g model hoge
Running via Spring preloader in process 59696
      invoke  active_record
The name 'Hoge' is either already used in your application or reserved by Ruby on Rails. Please choose an alternative and run this generator again.

原因

本来、アプリケーション名とモデル名を同じにすることができないことが原因と判明(参考

アプリケーション名を事前にHogeからHogeCoreに変更しているので、
アプリケーション名とモデル名が一致しないので問題ないように思える。

しかし、ここに大きな落とし穴があった!!!!

アプリケーション名の変更をLinuxコマンドのmvコマンドを実行してアプリケーションフォルダのみ変更したが、この変更方法に問題があった。
というより、もう1箇所変更しないといけない箇所がある。

解決方法

1. アプリケーションフォルダを変更する。

$ mv hoge hoge_core

2. 設定ファイルの名前空間を変更する。(参考)

変更前

config/application.rb
require_relative 'boot'
require 'rails/all'

Bundler.require(*Rails.groups)

module Hoge
  class Application < Rails::Application
    config.load_defaults 5.2
    # (省略)
  end
end

変更後

config/application.rb
require_relative 'boot'
require 'rails/all'

Bundler.require(*Rails.groups)

module HogeCore # この行の名前を変更!!!!!
  class Application < Rails::Application
    config.load_defaults 5.2
    # (省略)
  end
end

解消を確認

前項の解決方法を実施した後に再度Modelを作成すると成功する!

$ bundle exec rails g model hoge
Running via Spring preloader in process 61629
      invoke  active_record
      create    db/migrate/20181110124442_create_hoges.rb
      create    app/models/hoge.rb
      invoke    rspec
      create      spec/models/hoge_spec.rb
      invoke      factory_bot
      create        spec/factories/hoges.rb

まとめ

モデル名を変更できない場合は、モデル名とアプリケーション名だけではなく周辺設定(configファイル)を合わせて確認すると幸せになる。

よい、Railsライフを!!!

18
9
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
18
9