Jasdeep Singh
Jasdeep Singh

Reputation: 3326

Rails Migrations failed to specify Foreign Key in MySQL Table

 class CreateTestings < ActiveRecord::Migration
  def self.up
    create_table :testings do |t|
      t.string "name"
      t.boolean "visible"
      t.string "description"
      t.integer "roll"
      t.references "students"
      t.timestamps
    end
  end

  def self.down
     drop_table :testings
  end
end

Hello, i just ran this test migration to see how Rails handles Migrations. Even though i have t.references "students"

Rails created the students_id in my testings table successfully but however didn't specified any foreign key on it:

mysql> DESC testings;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| name        | varchar(255) | YES  |     | NULL    |                |
| visible     | tinyint(1)   | YES  |     | NULL    |                |
| description | varchar(255) | YES  |     | NULL    |                |
| roll        | int(11)      | YES  |     | NULL    |                |
| students_id | int(11)      | YES  |     | NULL    |                |
| created_at  | datetime     | YES  |     | NULL    |                |
| updated_at  | datetime     | YES  |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+

Is this how Rails works or otherwise i should've had

t.references :student instead of t.references "students"

Thanks!

Upvotes: 1

Views: 277

Answers (1)

Pan Thomakos
Pan Thomakos

Reputation: 34350

This is how rails works. It doesn't specify foreign key dependencies in its migrations. You'll have to do this manually with an 'execute' command and SQL code if you do want to specify foreign-key dependencies.

Upvotes: 2

Related Questions