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?
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">]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With