Rails 3 中的显式 require

发布于 2024-09-28 11:23:44 字数 839 浏览 3 评论 0原文

我正在将 Rails 2 应用程序转换为 Rails 3。到目前为止,我已经成功了。但是,有一个奇怪的问题,我必须明确要求任何外部文件。这是我原来的(即 Rails 2)ActiveRecord 模型:

class Book < ActiveRecord::Base
  belongs_to :author
  has_many :translations, :dependent => :destroy
  include Freebase
...
end

为了使其在 Rails 3 中工作,我必须需要模型 TranslationFreebase.rb 文件,因此:

class Book < ActiveRecord::Base
  require File.expand_path(File.dirname(__FILE__) + '/translation.rb')
  belongs_to :author
  has_many :translations, :dependent => :destroy
  require File.expand_path(File.dirname(__FILE__) + '../../../lib/freebase.rb')
  include Freebase
  ...
end

这是 Rails 3 中的正常方式,还是我做错了什么。换句话说,为什么需要显式包含这些文件?放置在 lib 文件夹中的 Freebase.rb 文件可能有某种原因,但是 Translation 模型又如何呢?在同一个目录中?

谢谢你们!

I am converting my Rails 2 app to Rails 3. So far, I've been successful. However, there is this strange issue that I have to explicitly require any external files. Here is my original (i.e. Rails 2) ActiveRecord model:

class Book < ActiveRecord::Base
  belongs_to :author
  has_many :translations, :dependent => :destroy
  include Freebase
...
end

in order to make it working in Rails 3, I have to require the model Translation and Freebase.rb file, thus:

class Book < ActiveRecord::Base
  require File.expand_path(File.dirname(__FILE__) + '/translation.rb')
  belongs_to :author
  has_many :translations, :dependent => :destroy
  require File.expand_path(File.dirname(__FILE__) + '../../../lib/freebase.rb')
  include Freebase
  ...
end

Is it the normal way in Rails 3, or I am doing something wrong. In other words, why is it necessary to explicitly include those files? There might probably be some reason for the Freebase.rb file, which is placed in the lib folder, but what about the Translation model which is in the same dir?

Thanks guys!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寄居人 2024-10-05 11:23:44

Rails 3 不像 Rails 2 那样自动加载。

打开 config/application.rb 并自定义如下所示的行:

# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)

在您的情况下,您可能想要

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

Rails 3 doesn't automatically autoload quite as much as Rails 2 did.

Open up config/application.rb and customize the line that looks like:

# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)

In your case, you probably want to have

config.autoload_paths += %W(#{config.root}/lib)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文