在您将此问题标记为重复之前,我已检查了其他相关问题:1,2,3,4和{{3基本上,所有这些都与加载lib
模块的方式相同,但User
仍然会引发错误。
模型/ user.rb
# This line throws an error:
# cannot load such file -- my-project-root/lib/model_with_properties.rb
require "#{Rails.root}/lib/model_with_properties.rb"
class User < ActiveRecord::Base
# This line throws an error:
# uninitialized constant User::ModelWithProperties
include ModelWithProperties
...
end
LIB / model_with_properties.rb
module ModelWithProperties
# Some functions
end
配置/ application.rb中
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require 'yaml'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Project
class Application < Rails::Application
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
# Load the lib folder, a thousand times
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]
config.autoload_paths << "#{Rails.root}/lib"
end
end
我错过了什么?
另一个有用的信息:
julian$ rails r 'puts ActiveSupport::Dependencies.autoload_paths'
Running via Spring preloader in process 38445
/my-project-root/lib
/my-project-root/lib/
/my-project-root/lib/assets/
/my-project-root/lib/tasks/
/my-project-root/app/assets
/my-project-root/app/controllers
/my-project-root/app/helpers
/my-project-root/app/jobs
/my-project-root/app/mailers
/my-project-root/app/models
/my-project-root/app/controllers/concerns
/my-project-root/app/models/concerns
/my-project-root/test/mailers/previews
julian$ rails -v
Rails 4.2.3
答案
非常感谢@jvillian,我使用的是RubyMine,我认为文件扩展名是隐藏的,所有重要的是IDE上的Ruby图标。实际上.rb
扩展名丢失了。
答案 0 :(得分:1)
在控制台中,执行Dir["lib/**/*.rb"]
以确保文件实际存在。修复后,尝试删除require
中的user.rb
语句(如@Stefan建议的那样)。并非完全必要,但require
语句有时会混淆AutoLoading。