add_column 用于引用(Rails) [英] add_column for references (Rails)
问题描述
我有以下完美运行的 Rails 迁移(删除了不相关的部分):
I have the following Rails migration which works perfectly (irrelevant pieces removed):
create_table :comments do |t|
t.text :body
t.references :post
end
现在我想在我的 comments
表(这是用户的用户 ID)中添加一个 author
列,但我不知道该怎么做(我很想只使用 execute
编写特定于 MySql 的语法).
Now I'd like to add an author
column to my comments
table (which is the userid of a user), but I have no idea how to do it (I'm tempted to just write the MySql-specific syntax using an execute
).
我一直在查看 add_column 这里不提references
.我实际上找到了 TableDefinition#references 但我不知道如何在 add_column
语句中使用它.
I've been looking at add_column here which doesn't mention references
. I've actually found TableDefinition#references but I have no idea how to use it with an add_column
statement.
这可能吗?另外,对于 MySql 来说,引用"功能实际上并没有在表之间建立关系是真的吗?
Is this possible? Also, is it true that, for MySql, the "references" functionality does not actually establish relationships between the tables?
推荐答案
虽然现在想从中得到任何点为时已晚,但我想我会为后代发布最好的方法:)
While it's too late to get any points out of this, I thought I'd post the best way for posterity :)
使用 change_table
而不是 create_table
将列添加到已经存在的表中,具有 TableDefinition 的所有优点:
use change_table
instead of create_table
to add columns to a table that already exists, with all the TableDefinition goodness:
self.up do
change_table :comments do |t|
t.references :author
end
end
这可能看起来微不足道,但像 Devise 这样的其他 gem 会大量使用他们自己的自定义表定义,这样您仍然可以使用它们.
This might seem trivial, but other gems like Devise make heavy use of their own custom table definitions, and this way you can still use them.
这篇关于add_column 用于引用(Rails)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!