Ruby 添加和删除引用的Rails迁移
使用Ruby 添加和删除引用的Rails迁移,ruby,ruby-on-rails-3,rails-migrations,Ruby,Ruby On Rails 3,Rails Migrations,使用rails generate migration AddClientToUser创建迁移文件后,我可以像这样编辑迁移文件: class AddClientToUser < ActiveRecord::Migration def self.up change_table :users do |t| t.references :client end end def self.down change_table :users do |t|
rails generate migration AddClientToUser
创建迁移文件后,我可以像这样编辑迁移文件:
class AddClientToUser < ActiveRecord::Migration
def self.up
change_table :users do |t|
t.references :client
end
end
def self.down
change_table :users do |t|
t.remove :client_id
end
end
end
类AddClientToUser这是反转迁移中添加的引用列的正确方法吗?没错!你也可以选择:
def self.down
remove_column :users, :client_id
end
在rails 4之后,您可以执行以下操作
class AddClientToUser < ActiveRecord::Migration
def change
add_reference :users, :client, index: true
end
end
类AddClientToUser它将为您处理上下操作,以及创建外键索引。您也可以使用来执行相反的操作。使用Rails 4,您只需键入: $rails生成迁移AddClientRefToUser客户端:引用 在控制台中,这将与Ryan所说的相同。Rails 4.2.1
rails g migration RemoveClientFromUsers client:references
将生成类似的迁移:
class RemoveClientFromUser < ActiveRecord::Migration
def change
remove_reference :users, :client, index: true, foreign_key: true
end
end
在非常change
方法中。
在保存对迁移的更改后,最后运行
rakedb:migrate
,将产生所需的结果。很高兴知道!我不确定引用是否有一些特殊的外键魔法,当该列被简单地删除时,它们不会被干净地处理掉。但是你的例子不就是remove\u column
而不是t.remove\u column
?你现在也可以使用remove\u references语法了。@BinaryPhile:remove\u reference
(单数)而不是'12年的remove\u references
@sampi我相信那是唯一的api,现在单数和复数都可以接受:我在rails@4.2.5
使用适配器mysql2@0.4.2
但它不起作用。它在外键约束中抛出所需的
mysql错误:(我认为应该是AddClientRefToUsers
它可以在末尾有或没有s,Rails足够智能,可以覆盖这两种情况,并将对Rail 5.2中的用户表进行更改,记住添加type::uuid
——如果在Rails 5及更高版本中设置ID列以实现向后兼容,那么您可以st需要添加\参考:用户,:型号\名称
默认添加索引
add_reference :users, :model_name, index: true, foreign_key: true