RailsNameError初期化されていない定数クラスソリューション



Rails Nameerror Uninitialized Constant Class Solution



問題

基本的に、これは、Railsコンソール/サーバーの起動時に構成がロードされていないクラスから関数を呼び出した場合に発生する可能性があります。

RailsプロジェクトのlibフォルダーにUtil.rbという名前のファイルを作成するとします。



Class Util def self.get_date Time.now.strftime(‘%F’) end end

そして、コマンドライン、つまりrails consoleを介して関数を呼び出したい場合は、おそらくrails consoleを起動し、次のようにクラス名Utilを使用してメソッドget_dateを呼び出します。

rails console > Util.get_date

これにより、次のエラーが発生します-
NameError:初期化されていない定数Util
これは、railsコンソールの起動時にクラスがロードされなかったことを意味します



解決

この問題を解決するには、クラスを環境にロードする必要があります。これは、次の方法で実行できます。

1.Railsプロジェクトのapplication.rbファイルを開きます
2.application.rbに次の行を追加します

config.autoload_paths += %W(#{config.root}/lib)

application.rbは次のようになります。



require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(:default, Rails.env) module RubyInRailsApp class Application ::Application # the new line added for autoload of lib config.autoload_paths += %W(#{config.root}/lib) # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run 'rake -D time' for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de end end

3.完了

結論

したがって、application.rbのconfigにautoload_pathsを設定すると、次のようになります。Railsプロジェクトのlibディレクトリにあるrubyファイルは、コンソールの起動時に自動的に読み込まれます。メソッドを呼び出しても、railsnameerrorの初期化されていない定数クラスエラーは発生しなくなりました。
ここで、メソッドを呼び出します-

Util.get_date

期待どおりの結果が返されます。コンソールの起動時にクラスに構成がロードされたため、名前解決は成功しました。

Railsアプリケーションを適切に構成すれば、最終的にこの種のエラーを減らすことができます。読んだ Railsアプリケーションの構成 構成について詳しく知るため。