简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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