add_column用于引用(Rails)

时间:2009-01-29 22:30:19

标签: ruby-on-rails schema

我有以下Rails迁移工作完美(删除了不相关的部分):

create_table :comments do |t|
  t.text :body
  t.references :post
end

现在我想在我的author表(用户的用户ID)中添加comments列,但我不知道该怎么做(我很想只需使用execute)编写MySql特定的语法。

我一直在关注add_column here,但没有提及references。我实际上找到了TableDefinition#references,但我不知道如何在add_column语句中使用它。

这可能吗?另外,对于MySql,“引用”功能是否真的没有在表之间建立关系?

6 个答案:

答案 0 :(得分:109)

虽然现在已经太晚了,但是我认为我会为后代发布最佳方式:)

使用change_table代替create_table将列添加到已存在的表中,并具有所有TableDefinition的优点:

self.up do
  change_table :comments do |t|
    t.references :author
  end
end

这看起来似乎微不足道,但是像Devise这样的其他宝石会大量使用自己的自定义表定义,这样你仍然可以使用它们。

答案 1 :(得分:78)

add_reference :table_name, :reference, index: true

答案 2 :(得分:34)

终于搞定了

add_column :locations, :state_id , :integer, :references => "states"

答案 3 :(得分:21)

首先,做:

script/generate migration AddAuthorIdToComments

打开生成的文件并添加以下行:

add_column :comments, :author_id, :integer

然后在您的模型文件中:

class User < ActiveRecord::Base
  has_many :comments, :foreign_key => "author_id"
end

class Comment
  belongs_to :author, :class_name => User
end

答案 4 :(得分:2)

自从我看过这个问题已经有一段时间了,但最后我检查了迁移不支持创建外键。但幸运的是,there is a plug-in for it。我已经习惯了,效果很好。

答案 5 :(得分:0)

您可以在新的迁移中添加add_column(:table, :column_name, :type, :options)列。