当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby - Rails include module in model trouble

问题描述:

I have module in /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

How to solve this trouble? Maybe it`s wrong to keep this types of files in /lib?

Environment:

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:

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.

网友答案:

when you define your class, you're "opening" a new scope. So when you do Models::Scopes, ruby is looking for User::Models::Scopes. You can fix this by using ::Models::Scopes, the :: telling ruby to look in the global scope.

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? Anyway, as you can see, I'm not yet familiar with those. You might want to dig on the subject if that interests you

分享给朋友:
您可能感兴趣的文章:
随机阅读: