Sql 如何向Rails Postgres迁移添加更新级联?
我需要编写一个Rails迁移,它将更新特定对象的uuid,然后将该id作为外键存储在所有行中,如下所示:Sql 如何向Rails Postgres迁移添加更新级联?,sql,ruby-on-rails,postgresql,foreign-keys,rails-migrations,Sql,Ruby On Rails,Postgresql,Foreign Keys,Rails Migrations,我需要编写一个Rails迁移,它将更新特定对象的uuid,然后将该id作为外键存储在所有行中,如下所示: alter table projects add constraint fk_league foreign key (user_id) references users(id) on update cascade 不幸的是,Rails似乎会自动生成约束: fk_rails_e4348431a9 我将如何编写上述sql来处理此问题?假设您在迁移中的某个地方有一个t.references或t
alter table projects add constraint fk_league
foreign key (user_id) references users(id) on update cascade
不幸的是,Rails似乎会自动生成约束:
fk_rails_e4348431a9
我将如何编写上述sql来处理此问题?假设您在迁移中的某个地方有一个
t.references
或t
t.references :user, :foreign_key => true
t.references
只是一个伪装的调用。add_reference
文档没有说明有关:foreign_key
选项的值的任何有用信息,但是:
因此,当您指定:foreign\u key
选项时,您可以将基础调用的选项散列交给它,其中包含:on\u update
选项:
:更新时
更新时发生的操作
。有效值为:null
,:cascade:
[sic]和:restrict
您可能希望将原始的t.references
调用替换为以下内容:
t.references :user, :foreign_key => { :on_update => :cascade }
如果您已经在生产中设置了所有内容,并且需要更改FK约束,那么我认为您需要手动修复:
添加迁移以删除原始约束并添加更新的约束:
def up
connection.execute(%q{
alter table projects
drop constraint fk_rails_e4348431a9
})
connection.execute(%q{
alter table projects
add constraint fk_rails_e4348431a9
foreign key (user_id)
references users(id)
on update cascade
})
end
def down
# The opposite of the above...
end
您可能不需要保留Rails选择的约束名称,但也可以这样做
手动编辑您的db/schema.rb
以将上述:foreign\u key=>{:on\u update=>:cascade}
添加到相应的t.references
调用中
谢谢我希望有一种方法可以只在我更新主键的表中指定它,然后进行更新自动级联,但是我必须用很难的方法来完成。这应该行得通。
def up
connection.execute(%q{
alter table projects
drop constraint fk_rails_e4348431a9
})
connection.execute(%q{
alter table projects
add constraint fk_rails_e4348431a9
foreign key (user_id)
references users(id)
on update cascade
})
end
def down
# The opposite of the above...
end