【问题标题】:How do I add an UPDATE CASCADE to a Rails-Postgres migration?如何将 UPDATE CASCADE 添加到 Rails-Postgres 迁移?
【发布时间】:2015-08-28 19:59:13
【问题描述】:

我需要编写一个 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 来处理这个问题?

【问题讨论】:

    标签: sql ruby-on-rails postgresql foreign-keys rails-migrations


    【解决方案1】:

    大概你的迁移中有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
    发生的动作ON UPDATE。有效值为 :nullify、:cascade: [原文如此] 和 :restrict

    您希望将原来的 t.references 电话替换为类似这样的电话:

    t.references :user, :foreign_key => { :on_update => :cascade }
    

    如果您已经在生产环境中进行了所有设置并且需要更改 FK 约束,那么我认为您需要手动解决问题:

    1. 添加迁移以删除原始约束并添加更新的约束:

      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 选择的约束名称,但您也可以这样做。

    2. 手动编辑您的db/schema.rb,将上述:foreign_key => { :on_update => :cascade } 添加到相应的t.references 调用中。

    【讨论】:

    • 谢谢!我希望有一种方法可以仅在我正在更新主键的表上指定它,然后让更新自动级联,但我将不得不以艰难的方式做到这一点。这应该有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 2019-11-05
    相关资源
    最近更新 更多