我创建了一个简单的示例作为健全性检查,但似乎仍然无法破坏 rails 中 has_and_belongs_to_many 关系两侧的项目。
每当我尝试从任一表中删除对象时,都会收到可怕的 NameError /“未初始化常量”错误消息。
为了演示,我创建了一个带有 Boy 类和 Dog 类的示例 rails 应用程序。我为每一个都使用了基本的脚手架,并创建了一个名为boys_dogs 的链接表。然后,我添加了一个简单的 before_save 例程,以在任何时候创建一个男孩并建立关系时创建一个新的“狗”,以便轻松设置。
狗.rb
class Dog < ActiveRecord::Base
has_and_belongs_to_many :Boys
end
男孩.rb
class Boy < ActiveRecord::Base
has_and_belongs_to_many :Dogs
def before_save
self.Dogs.build( :name => "Rover" )
end
end
架构.rb
ActiveRecord::Schema.define(:version => 20100118034401) do
create_table "boys", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "boys_dogs", :id => false, :force => true do |t|
t.integer "boy_id"
t.integer "dog_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "dogs", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
end
我在这里和其他地方看到了很多关于类似问题的帖子,但解决方案通常使用belongs_to 并且复数/单数类名被混淆。我不认为这里是这种情况,但我尝试将 habtm 语句切换为使用单数名称只是为了看看它是否有帮助(没有运气)。我似乎在这里遗漏了一些简单的东西。
实际的错误信息是:
BoysController#destroy
未初始化常量 Boy::Dogs 中的 NameError
跟踪看起来像:
/Library/Ruby/Gems/1.8/gems/activesupport-2.3.4/lib/active_support/dependencies.rb:105:in destroy_without_callbacks' /Library/Ruby/Gems/1.8/gems/activerecord-2.3.4/lib/active_record /callbacks.rb:337:in发送' ...
const_missing'
(eval):3:indestroy_without_transactions'
/Library/Ruby/Gems/1.8/gems/activerecord-2.3.4/lib/active_record/transactions.rb:229:in
谢谢。