【问题标题】:Access Models in subfolders访问子文件夹中的模型
【发布时间】:2012-09-16 18:07:54
【问题描述】:

我在访问子文件夹中的模型时遇到了这个问题。我的项目中有以下文件结构:

app/models
   - accounts
     - type1.rb #Inherits from Account
     - type2.rb #Inherits from Account
     - etc.   
   - account.rb
   - user.rb
   - etc.

现在在 user.rb 中,我有一个尝试创建 type1 或 type2 帐户的函数:

def function
   self.account = ::Type1.new(...)
end

知道我在 application.rb 中添加了以下行(在 http://blog.hasmanythrough.com/2008/5/6/a-simple-alternative-to-namespaced-models 之后):

config.autoload_paths += Dir["#{config.root}/app/models/**/"]

以便确实加载模型子文件夹。

现在,当我调用该函数时,我仍然收到著名的uninitialized constant Type1 错误消息。我错过了什么?

更新:

Type1 类为空:

class Type1 < Account
end

Account 类很简单:

class Account < ActiveRecord::Base

#======================RELATIONS======================
  belongs_to :currency
  belongs_to :organization

#======================VALIDATIONS=========================
  validates :name, :presence => true
  validates :country, :presence => true
  validates :currency, :presence => true
  validates :organization, :presence => true
end

【问题讨论】:

    标签: ruby-on-rails-3


    【解决方案1】:

    试试这个

    config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**}')]
    

    【讨论】:

    • 不,我已经试过了。我还通过转储 config.autoload_paths 变量检查了该文件夹是否已添加到路径中:C:/Users/.../lib C:/Users/.../app/models/ C:/Users/.../app/models/accounts/
    • 你有 type1 所属的命名空间吗?
    • 不,我删除了它:class Type1 &lt; Account
    • 所以 account 只是一个文件夹名,那么你必须试试这个代码 -- config.load_paths += Dir["#{RAILS_ROOT}/app/models/*"].find_all { |f| File.stat(f).目录? }
    • 该文件夹已正确添加,但无论如何我测试了您的代码(只是为了看看),它产生了相同的路径列表。所以问题仍然存在。我猜问题不是来自 config.autoload_paths 中缺少的路径。
    【解决方案2】:

    好的,我终于找到了。这个想法来自这个页面:Rails 3 library not loading until require

    我的问题实际上是文件名 wat 不尊重类的 CamelCase 名称...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-04
      • 2013-08-01
      • 2018-11-16
      • 2015-11-12
      • 2013-05-22
      • 1970-01-01
      • 2014-05-04
      • 1970-01-01
      相关资源
      最近更新 更多