Rails 3中的显式需求

Alb*_*ore 4 ruby-on-rails upgrade require

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

class Book < ActiveRecord::Base
  belongs_to :author
  has_many :translations, :dependent => :destroy
  include Freebase
...
end
Run Code Online (Sandbox Code Playgroud)

为了使它在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
Run Code Online (Sandbox Code Playgroud)

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

多谢你们!

ben*_*sie 5

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)
Run Code Online (Sandbox Code Playgroud)

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

config.autoload_paths += %W(#{config.root}/lib)
Run Code Online (Sandbox Code Playgroud)