从 Rails 3 项目的 lib 目录中访问模型 [英] Accessing models from within the lib directory in a Rails 3 project

查看:32
本文介绍了从 Rails 3 项目的 lib 目录中访问模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 lib 目录中有一个文件,它使用了模型中定义的一些常量,例如:

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
end

然后我在 lib/foo.rb

and then I have in lib/foo.rb

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

由于找不到用户类而失败.如何在 lib 上的该文件之前加载 User?

It fails due to not finding the class User. How can I load User before that file on lib?

我正在通过在 application.rb 中加载该文件来加载该文件:

I'm loading that file by having this in my application.rb:

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

推荐答案

解决方案是,我在/lib 中的文件实际上是一个 rake 文件所需要的,而且似乎在整个自动加载系统之前加载了 rake 文件是由 Rails 设置的,所以它找不到模型.从 .rake 文件中删除 require 后,一切都开始工作了.

The solution was, that my file in /lib was actually being required by a rake file, and it seems rake files are loaded before the whole auto-load system is setup by Rails, so it couldn't find the model. After I remove the require from the .rake file, everything started working.

这篇关于从 Rails 3 项目的 lib 目录中访问模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆