我需要编写一个 Rails 迁移来更新特定对象的 uuid,然后通过所有将该 id 存储为外键的行进行 CASCADE,如下所示:
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.belongs_to
:
t.references :user, :foreign_key => true
t.references
只是一个 add_reference
变相打电话。 add_reference
文档没有说明有关 :foreign_key
选项值的任何有用信息,但 the code做:
foreign_key_options = options.delete(:foreign_key)
#...
if foreign_key_options
to_table = Base.pluralize_table_names ? ref_name.to_s.pluralize : ref_name
add_foreign_key(table_name, to_table, foreign_key_options.is_a?(Hash) ? foreign_key_options : {})
end
因此,当您指定 :foreign_key
选项时,您可以将底层 add_foreign_key
的选项散列传递给它调用并且有一个 :on_update
选项:
:on_update
Action that happensON UPDATE
. Valid values are:nullify
,:cascade:
[sic] and: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_key => { :on_update => :cascade }
添加到适当的t.references
调用。
关于sql - 如何将 UPDATE CASCADE 添加到 Rails-Postgres 迁移中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32278912/