模块只是没有加载到模型[Rails]中

时间:2016-02-12 14:55:36

标签: ruby-on-rails ruby module

在您将此问题标记为重复之前,我已检查了其他相关问题:1234和{{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扩展名丢失了。

5

1 个答案:

答案 0 :(得分:1)

在控制台中,执行Dir["lib/**/*.rb"]以确保文件实际存在。修复后,尝试删除require中的user.rb语句(如@Stefan建议的那样)。并非完全必要,但require语句有时会混淆AutoLoading。