简体   繁体   English

Rails包含模型故障中的模块

[英]Rails include module in model trouble

I have module in /lib/models/scopes.rb 我在/lib/models/scopes.rb中有模块

module Models
    module Scopes
        extend ActiveSupport::Concern
        ...
    end
end

I'm trying to include it from model: 我正在尝试将其包含在模型中:

class User < ActiveRecord::Base
  include Models::Scopes
end

And getting error: 并得到错误:

NameError: uninitialized constant User::Models NameError:未初始化的常量User :: Models

How to solve this trouble? 如何解决这个麻烦? Maybe it`s wrong to keep this types of files in /lib? 将此类文件保存在/ lib中也许是错误的?

Environment: Rails v3.1 Ruby v1.9.3 环境:Rails v3.1 Ruby v1.9.3

Rails doesn't require files in the lib directory automatically, but you can add to the autoloaded paths in config/application.rb : Rails不需要lib目录中的文件,但是您可以在config/application.rb添加到自动加载的路径中:

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

Restart the server to pick up the new settings. 重新启动服务器以获取新设置。

This will now load the file automatically when the module name is first used. 现在,当首次使用模块名称时,它将自动加载文件。 In development mode, you might want to reload the module after every change in order to see the changes without restarting the server. 在开发模式下,您可能希望在每次更改后重新加载模块,以便在不重新启动服务器的情况下查看更改。 To do that, add it as an eager load path instead: 为此,请将其添加为热切的加载路径:

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

The scope shouldn't be a problem as long as you don't have a Models class or module within User or anywhere else. 只要您 User或其他任何地方都没有Models类或模块, 范围就不成问题。

when you define your class, you're "opening" a new scope. 当您定义类时,您是在“打开”一个新的作用域。 So when you do Models::Scopes , ruby is looking for User::Models::Scopes . 因此,当您执行Models::Scopes ,ruby正在寻找User::Models::Scopes You can fix this by using ::Models::Scopes , the :: telling ruby to look in the global scope. 您可以通过使用修复此::Models::Scopes ,该::告诉红宝石在全球范围内寻找。

FYI: I'm not sure about the terms I used or even if my train of thought if correct; 仅供参考:我不确定我使用的术语,甚至不确定我的思路是否正确; but the solution should be good anyway. 但无论如何,解决方案应该很好。 I'd think Ruby would try for ::Models::Scope after failing to find User::Models::Scope , but it doesn't.. Maybe there is a User::Models scope defined somewhere? 我认为Ruby在找不到User::Models::Scope ::Models::Scope后会尝试User::Models::Scope ,但事实并非如此。也许某个地方定义了User::Models范围? Anyway, as you can see, I'm not yet familiar with those. 无论如何,如您所见,我还不熟悉这些内容。 You might want to dig on the subject if that interests you 如果您感兴趣,您可能想研究这个主题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM