Ruby-on-rails add_column 用于引用(Rails)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/493777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
add_column for references (Rails)
提问by Dan Rosenstark
I have the following Rails migration which works perfectly (irrelevant pieces removed):
我有以下完美运行的 Rails 迁移(删除了不相关的部分):
create_table :comments do |t|
t.text :body
t.references :post
end
Now I'd like to add an authorcolumn to my commentstable (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).
现在我想author在我的comments表中添加一列(这是用户的用户 ID),但我不知道该怎么做(我很想只使用 编写 MySql 特定的语法execute)。
I've been looking at add_column herewhich doesn't mention references. I've actually found TableDefinition#referencesbut I have no idea how to use it with an add_columnstatement.
我一直在查看 add_column此处没有提到references. 我实际上已经找到了TableDefinition#references但我不知道如何在add_column语句中使用它。
Is this possible? Also, is it true that, for MySql, the "references" functionality does not actually establish relationships between the tables?
这可能吗?另外,对于 MySql,“引用”功能实际上并没有在表之间建立关系,这是真的吗?
回答by Jaime Bellmyer
While it's too late to get any points out of this, I thought I'd post the best way for posterity :)
虽然现在已经太晚了,但我想我会为后代发布最好的方法:)
use change_tableinstead of create_tableto add columns to a table that already exists, with all the TableDefinition goodness:
使用change_table而不是create_table将列添加到已经存在的表中,具有 TableDefinition 的所有优点:
self.up do
change_table :comments do |t|
t.references :author
end
end
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.
这可能看起来微不足道,但是像 Devise 这样的其他 gem 大量使用他们自己的自定义表定义,这样您仍然可以使用它们。
回答by Rajeev Kannav Sharma
add_reference :table_name, :reference, index: true
回答by Swapnil Chincholkar
Finally got it
终于明白了
add_column :locations, :state_id , :integer, :references => "states"
回答by Milan Novota
First, do:
首先,做:
script/generate migration AddAuthorIdToComments
Open the generated file and add this line:
打开生成的文件并添加以下行:
add_column :comments, :author_id, :integer
Then in your model files:
然后在您的模型文件中:
class User < ActiveRecord::Base
has_many :comments, :foreign_key => "author_id"
end
class Comment
belongs_to :author, :class_name => User
end
回答by Craig Stuntz
It's been a while since I've looked at this, but last I checked migrations don't support creating foreign keys. Fortunately, however, there is a plug-in for it. I've used this and it works well.
自从我看过这个已经有一段时间了,但最后我检查了迁移不支持创建外键。然而,幸运的是,有一个插件。我用过这个,效果很好。
回答by Craig Stuntz
You could add the column by add_column(:table, :column_name, :type, :options)in a new Migration.
您可以add_column(:table, :column_name, :type, :options)在新的迁移中添加列。

