Accessing models from within the lib directory in a Rails 3 project

后端 未结 5 734
天涯浪人
天涯浪人 2021-01-03 06:04

I have a file in the lib directory that uses some constants defined in a model, like:

class User < ActiveRecord::Base
   MAX_EMAIL_ADDRESS_LENGTH = 255
en         


        
5条回答
  •  轮回少年
    2021-01-03 06:32

    By default, YourApplicationNameHere::Application.autoload_paths is []. I (purely for organizational reasons) add a glob for my app/models directory too.

    config.autoload_paths += Dir["#{Rails.root}/app/models/**/"]
    config.autoload_paths += Dir["#{config.root}/lib"]
    

    With this setup I'm able to do what you're asking in the Question without trouble. This should benefit you as well, telling Rails where to look if it can't find the User model from within your lib/ module's instantiation.

    Edit

    Specifying the exact error message in your question would have helped too.

    uninitialized constant Foo::User
    

    means Ruby/Rails is looking for User within the Foo namespace. Prefix User with :: to force the lookup to the global namespace.

    module Foo
      LONG_EMAIL_ADDRESS = "foo@bar.com".rjust(::User::MAX_EMAIL_ADDRESS_LENGTH, "a")
    end
    

提交回复
热议问题