Foreign key in rails 4
foreign-keys, rails-migrations, ruby-on-rails, ruby-on-rails-4, sqlite
Solution
According to Ruby on Rails 4.2 Release notes, only the mysql, mysql2 and postgresql adapters support foreign keys.
Unfortunately, the sqlite3 adapter does not.
Problem
I'm using Rails 4 and SQLite. I'm trying to add foreing keys to my `indicators` table. Please see my code below ``` class Indicator < ActiveRecord::Base belongs_to :objetive belongs_to :responsible, class_name: "Person" end ``` The migration script: ``` class AddFksToIndicator < ActiveRecord::Migration def change add_reference :indicators, :objective, index: true add_reference :indicators, :responsible, index: true end end ``` when run the migration all is ok, so I tried in console: ``` 2.0.0p247 :002 > i = Indicator.new => #<Indicator id: nil, name: nil, created_at: nil, updated_at: nil, objective_id: nil, responsible_id: nil> 2.0.0p247 :002 > i.objective_id = 0 2.0.0p247 :003 > i.save ``` To my surprise, the indicator was saved and there is no `obective` with id = 0. Finally, I checked the indicators table schema and I get: ``` CREATE TABLE "indicators" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255), "created_at" datetime, "updated_at" datetime, "objective_id" integer, "responsible_id" integer); CREATE INDEX "index_indicators_on_objective_id" ON "indicators" ("objective_id"); CREATE INDEX "index_indicators_on_responsible_id" ON "indicators" ("responsible_id"); ``` Why there is no foreign key constraint on `objective_id` and `responsible_id`? Am I doing something wrong?