1

私は2つのモデル、LaserSheetItemhas_many関係でお互いに関係があります:彼らは多対多の関係を持っているのでカスケード削除を使用せずに外部キーを持つActive Recordオブジェクトを削除するにはどうすればよいですか?

class LaserSheet < ActiveRecord::Base 
    belongs_to :job 
    has_many :items 
    ... 
end 

class Item < ActiveRecord::Base 
    belongs_to :job 
    has_many :laser_sheets 
    ... 
end 

を、私は削除せずにItemを削除できるようにしたいですそのLaserSheets関連、同様にその関連Itemsを削除せずLaserSheetを削除します。

ERROR: update or delete on table "items" violates foreign key constraint "fk_rails_f7f551ebf9" on table "laser_sheets" DETAIL: Key (id)=(293) is still referenced from table "laser_sheets". 

EDIT::二つのモデル間の参照文献を追加

DBの移行:

class AddItemRefToLaserSheets < ActiveRecord::Migration 
    def change 
    add_reference :laser_sheets, :item 
    end 
end 

class AddLaserSheetRefToItems < ActiveRecord::Migration 
    def change 
    add_reference :items, :laser_sheet 
    end 
end 
+1

:あなたのような何かをしたい場合がありますか? – Ryan

+1

はい、 'has_and_belongs_to_many'のように見えます。 –

答えて

2

チェック私はオブジェクトの1つを削除しようとしたときしかし、私は外部キーエラーが発生しますdependent optionsを送信してください。これらはhas_and_belongs_to_many` `でなければならず、代わりに` has_many`関係の

class LaserSheet < ActiveRecord::Base 
    has_many :items, dependent: :nullify 
    ... 

class Item < ActiveRecord::Base 
    has_many :laser_sheets, dependent: :nullify 
    ... 
関連する問題