gpt4 book ai didi

ruby-on-rails - 获取名称错误: uninitialized constant when trying to assign belongs_to

转载 作者:行者123 更新时间:2023-12-02 17:45:49 31 4
gpt4 key购买 nike

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

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, ...>

出于某种原因,我可以获得关联的房间,但无法分配新的房间。我在这里错过了什么?

最佳答案

您需要确保您的模型位于 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">]

关于ruby-on-rails - 获取名称错误: uninitialized constant when trying to assign belongs_to,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34331000/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com