no_picture

Rails で外部キー制約

外部キー制約は好きですか? O/RマッパーしててもなるべくDBの力は借りたいです。 ということで、Ruby Toolboxで foreign を検索して、ちらちら見て一番人気のforeignerを選びました。基本的にはデータベースに丸投げなので Rails4 でもいまのとこ問題なく使えております。 インストールは Gemfile に: gem 'foreigner' と追加して bundle install あとはマイグレーションで: create_table :comments do |t| t.references :post, null: false, index: true t.foreign_key :posts, dependent: :delete end としておきました。 ついでに確認。 存在しない 外部キーを指定すると保存を失敗する確認。postgresの例: Comment.create(post_id: 1) # => PG::Error: ERROR: insert or update on table "comments" violates foreign key constraint "comments_post_id_fk" キーを指定して、親になるオブジェクトを削除すると消える確認: Comment.create(post_id: Post.create) Comment.count # => 1 Post.count # => 1 Post.first.destroy Post.count # => 0 Comment.count