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

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

    It appears that your class User has not be instantiated, which seems unusual, unless you have 'user.rb' in a location other than 'models'. It is often the case that classes aren't loaded in development unless they are specifically in that directory, but one solution I use is this line that you could put just within your code that you expect to be called prior to the offending line you have..

    Rails.application.eager_load! if Rails.env == "development"
    

    The conditional part is probably unnecessary, but I include it just to be certain its effect only occurs in development.

提交回复
热议问题