/home/filipe/.rvm/gems/ruby-2.7.1/gems/zeitwerk-2.60/lib/zeitwerk/loader.rb:359:在"set_autoloads_in_dir中的块中救援"中:错误的常量名称Usersession.controller由模块从文件(zeitwerk::NameError(推断
解决此问题的可能方法:
- 告诉Zeitwerk忽略此特定文件
- 告诉Zeitwerk忽略它的一个父目录
- 重命名文件以符合命名约定
- 修改屈折符来处理这种情况
usersession.controller.rb:
class SessionsController < ApplicationController
def new
redirect_to user_contacts_path(current_user) if user_signed_in?
end
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
sign_in(user)
redirect_to user_contacts_path(current_user)
else
flash.now[:danger] = 'Email e Senha inválidos'
render 'new'
end
end
def destroy
sign_out
flash[:warning] = 'Logout realizado com sucesso'
redirect_to entrar_path
end
end
application.rb:
require_relative "boot"
require "rails/all"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module App
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 7.0
# Configuration for the application, engines, and railties goes here.
#
# These settings can be overridden in specific environments using the files
# in config/environments, which are processed later.
#
# config.time_zone = "Central Time (US & Canada)"
# config.eager_load_paths << Rails.root.join("extras")
end
end
在我看来,您面临的问题是因为控制器的文件名与类不同:usersesions.controller!=会话控制器。Zeitwerk使用文件名来查找类。你有两个选择:
- 将文件重命名为sessions_controller.rb
- 将SessionsController重命名为UsersessionController。附言:记得更换"用"_"文件名中。例如:usersessions_controller,而不是usersessions.controller
完成此操作后,重新启动服务器。
为什么会发生此错误?因为我们没有遵循Zeitwerk惯例:
要获得Zeitwerk可以使用的文件结构,只需在文件和目录定义的类和模块的名称之后命名文件和目录。
示例:
lib/my_gem.rb -> MyGem
lib/my_gem/foo.rb -> MyGem::Foo
lib/my_gem/bar_baz.rb -> MyGem::BarBaz
lib/my_gem/woo/zoo.rb -> MyGem::Woo::Zoo
参考:https://github.com/fxn/zeitwerk#file-结构