LoginSignup
34
30

More than 5 years have passed since last update.

外部キー制約でハマったので(rails)

Last updated at Posted at 2017-02-19

railsで掲示板を作っているときに外部キー制約がわからなくてハマったのでメモ。

前提

  • スレッドを投稿でき、各スレッドにコメントができる掲示板を作っている
  • スレッド(my_threadsテーブル)とコメント(commentsテーブル)はthread_idで紐づけられている(以下参照)
class CreateComments < ActiveRecord::Migration[5.0]
  def change
    create_table :comments do |t|
      t.string :content
      t.references :my_thread, foreign_key: true

      t.timestamps
    end
  end
end

外部キー制約の書き方はこっち

ハマったこと

my_threads_controller.rb
def destroy
  @my_thread.destroy
  redirect_to my_threads_url, notice: 'My thread was successfully destroyed.'
end

としても
Cannot delete or update a parent row: a foreign key constraint fails
ってでてきてスレッドの削除ができない。

原因

外部キー制約を定義すると参照整合性が保証される

参照整合性とは

外部キーテーブルのデータへのリンクが無効になるような変更を主キーテーブルのデータに加えることができない

つまり、主キーのない外部キーがあってはならないので
外部キーを残したまま主キーを消そうとするとエラーになる

参照整合性についてはこっち

解決策

has_manyの後にdependentオプションを追加

class MyThread < ApplicationRecord
  has_many :comments, dependent: :destroy
  validates :title, presence: { message: "入力してください" }
end

Railsガイドの下の方に書いてある

こうすることで
関連付けられたオブジェクトもすべて同時にdestroy
してくれる

34
30
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
30