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

后端 未结 5 731
天涯浪人
天涯浪人 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:13

    The first part was done right:

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

    Next, it is important, module

    module Foo
      ...
    end
    

    must be placed into

    lib/foo.rb
    

    file.

    And then, it can be included into application code.

    class Comment < ActiveRecord::Base
      include Foo
      ...
    end
    

    If file foo.rb from lib directory is not intended to be included (however it is probably a wrong way), then to use Rails models and other stuff inside this code you should put this into foo.rb:

    require_relative "../config/environment.rb"
    

提交回复
热议问题