今天我决定重组大量的用户相关模型,我有一个问题.
在我有这样的结构之前:
app/models/user.rb app/models/user_info.rb app/models/user_file.rb ...
app/models/user.rb app/models/user/info.rb app/models/user/file.rb ...
并将其定义改为
class User::Info < ActiveRecord::Base class User::File < ActiveRecord::Base ...
用户模型未更改(关联除外).
除了User :: File模式,一切都可以正常工作.当我试图访问这个模型,我得到以下错误:
warning: toplevel constant File referenced by User::File
确实它返回标准的ruby File类.
我做错了什么?
UPD1:
root# rails c Loading development environment (Rails 3.2.13) 2.0.0p195 :001 > User::File (irb):1: warning: toplevel constant File referenced by User::File => File 2.0.0p195 :002 > User::Info => User::Info(...)
UPD2:
2.0.0p195 :001 > User::SomeModel NameError: uninitialized constant User::SomeModel 2.0.0p195 :002 > User::IO (irb):2: warning: toplevel constant IO referenced by User::IO => IO 2.0.0p195 :003 > User::Kernel (irb):3: warning: toplevel constant Kernel referenced by User::Kernel => Kernel
我的应用程序没有任何IO或内核类,除了ruby默认.
UPD3:
# app/models/user.rb class User < ActiveRecord::Base has_many :files,class_name: 'User::File' .. end # app/models/user/file.rb class User::File < ActiveRecord::Base belongs_to :user # some validations,nothing serIoUs end
解决方法
您的User :: File类未加载.您必须要求它(例如在user.rb中).
当ruby / rails看到User :: Info并对其进行评估时(简化;仅用户定义),会发生以下情况.
>检查User :: Info是否被定义 – 它不是(还)
>检查信息是否被定义 – 它不是(还)
>未初始化常数 – >做rails魔术找到用户/ info.rb文件并要求它
>返回User :: Info
现在让我们再次为User :: File
检查User :: File是否被定义 – 它不是(还)
>检查文件是否被定义 – 它是(因为ruby有一个内置的File类)!
>产生警告,因为我们被要求User :: File,但是:: File
> return :: File