サニティチェックとして簡単な例を作成しましたが、レールの has_and_belongs_to_many 関係のどちらの側でもアイテムを破棄できないようです。
いずれかのテーブルからオブジェクトを削除しようとするたびに、恐ろしい NameError / "uninitialized constant" エラー メッセージが表示されます。
実例を示すために、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
schema.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
ここや他の場所で同様の問題について多くの投稿を見てきましたが、解決策は通常、属しているクラス名を使用しており、複数形/単数形のクラス名が混乱しています。ここではそうではないと思いますが、habtm ステートメントを切り替えて単数形の名前を使用して、それが役立つかどうかを確認してみました (うまくいきませんでした)。ここで単純なものが欠けているようです。
実際のエラー メッセージは次のとおりです。
BoysController の NameError#destroy
未初期化定数 Boy::Dogs
トレースは次のようになります。
/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 send' ...
const_missing'
(eval):3:indestroy_without_transactions'
/Library/Ruby/Gems/1.8/gems/activerecord-2.3.4/lib/active_record/transactions.rb:229:in
ありがとう。