Cristhian Boujon
Cristhian Boujon

Reputation: 4190

Foreign key in rails 4

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?

Upvotes: 6

Views: 2138

Answers (2)

michaeldwp
michaeldwp

Reputation: 431

When you're using add_reference, you'd need to add foreign_key: true to to get foreign key support with that call. For example:

add_reference :indicators, :objective, index: true, foreign_key: true

The default is foreign_key: false, as mentioned in the docs here.

Since you've already created your migration without a foreign key, you'll need to create another migration with a call to add_foreign_key.

For example:

def change
   # add_foreign_key(from_table, to_table)
   add_foreign_key :indicators, :objectives
end

Here's the documentation for add_foreign_key.

Hope this helps.

Upvotes: 0

Tsutomu
Tsutomu

Reputation: 5148

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.

Upvotes: 9

Related Questions