Rails迁移无法在MySQL表中指定外键

时间:2011-02-01 03:56:56

标签: ruby-on-rails translation

 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

您好,我刚刚运行此测试迁移,以了解Rails如何处理迁移。即使我有 t.references "students"

Rails在我的测试表中成功创建了students_id但是没有在其上指定任何外键:

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    |                |
+-------------+--------------+------+-----+---------+----------------+

这是Rails的工作原理还是我应该有的

t.references :student代替t.references "students"

谢谢!

1 个答案:

答案 0 :(得分:2)

这就是rails的工作原理。它没有在迁移中指定外键依赖项。如果您想要指定外键依赖项,则必须使用'execute'命令和SQL代码手动执行此操作。