Rails 迁移未能在 MySQL 表中指定外键
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"
谢谢!
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 havet.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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这就是 Rails 的工作原理。它在迁移中没有指定外键依赖项。如果您确实想要指定外键依赖项,则必须使用“执行”命令和 SQL 代码手动执行此操作。
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.