获取NameError:尝试分配belongs_to时未初始化的常量

时间:2015-12-17 09:29:15

标签: ruby-on-rails activerecord associations

我有两个模型,如下所示:

module MainModule
  module SubModule
    class Home < ActiveRecord::Base
      has_many :rooms
    end
  end
end

module MainModule
  module SubModule
    class Room < ActiveRecord::Base
      belongs_to :home
    end
  end
end

如果我执行以下操作,则会收到错误消息:

> home.rooms << room
=> NameError: uninitialized constant Room
(Failed)
> home.rooms
=>  #<ActiveRecord::Associations::CollectionProxy []> 
(Success)

但如果我更新Home模型:

..
has_many :rooms, class_name: "MainModule::SubModule::Room"
..
> home.rooms << room
=> #<MainModule::SubModule::Room id: 1, ...>

出于某种原因,我可以获得相关的房间但不能分配新房间。我在这里想念的是什么?

2 个答案:

答案 0 :(得分:1)

您需要确保您的模型位于Rails中app / models目录下的子目录中。我有这样的事情:

$ ls -1R app/models
  main_module

  app/models/main_module:
  sub_module

  app/models/main_module/sub_module:
  home.rb
  room.rb

通过这种结构,我能够在Rails控制台中执行以下操作:

irb(main):001:0> home = MainModule::SubModule::Home.new
=> #<MainModule::SubModule::Home id: nil, name: nil, created_at: nil, updated_at: nil>
irb(main):002:0> home.name = 'Home'
=> "Home"
irb(main):003:0> home.save
=> true
irb(main):004:0> room = MainModule::SubModule::Room.new
=> #<MainModule::SubModule::Room id: nil, name: nil, home_id: nil, created_at: nil, updated_at: nil>
irb(main):005:0> room.name = 'Room'
=> "Room"
irb(main):006:0> room.save
=> true
irb(main):007:0> home.rooms << room
=> [#<MainModule::SubModule::Room id: 1, name: "Room", home_id: 1, created_at: "2016-01-06 14:28:06", updated_at: "2016-01-06 14:28:13">]

答案 1 :(得分:0)

以下情况如何(我还没有尝试过):

module MainModule
  module SubModule
    class Home < ActiveRecord::Base
      has_many :rooms
    end
  end
end

module MainModule
  module SubModule
    class Room < ActiveRecord::Base
      belongs_to :home
    end
  end
end