Tar_Tw45
Tar_Tw45

Reputation: 3222

Getting NameError: uninitialized constant when trying to assign belongs_to

I have two models like the following:

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

if I do the following, I get an error:

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

But if I update the Home model:

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

For some reason, I can get the associated rooms but can't assign a new one. What did I miss here?

Upvotes: 9

Views: 1068

Answers (2)

Mike Gorski
Mike Gorski

Reputation: 1228

You'll need to make sure your models are in subdirectories under the app/models directory in Rails. I have something like this:

$ ls -1R app/models
  main_module

  app/models/main_module:
  sub_module

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

With that structure, I was able to do the following in the Rails console:

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">]

Upvotes: 1

atw
atw

Reputation: 5830

How about the following(I haven't tried it):

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

Upvotes: 0

Related Questions