由于 Rails 中没有任何默认值,change_column_default 的可逆迁移 [英] Reversible migration for change_column_default from not having any default in Rails

查看:44
本文介绍了由于 Rails 中没有任何默认值,change_column_default 的可逆迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rails 活动记录迁移指南 说你可以做到>

The Rails guides to active record migrations says that you can do

change_column_default :products, :approved, from: true, to: false

我在 Rails 中有一个 change 方法,类似于以下内容:

I've got a change method in Rails that's similar to the following:

change_column_default :people, :height, from: nil, to: 0

旨在从没有任何默认值变为默认值为零.

with the intention of going from not having any defaults, to having a default of zero.

但是,当我尝试回滚它时,我得到

However, when I try rolling it back, I get

ActiveRecord::IrreversibleMigration: ActiveRecord::IrreversibleMigration

考虑到我给 Rails 一个 fromto,为什么它不接受?

Considering I give Rails a from and to, why isn't it accepting it?

我使用的是 Rails 4.2.0.

I'm using Rails 4.2.0.

推荐答案

使用 fromto在 Rails 5+ 中添加

问题中链接的指南适用于 Edge Rails,而不适用于已发布的 Rails 版本.

Using from and to was added in Rails 5+

The guide linked to in the question is for Edge Rails, not for a released version of Rails.

change_column_default 的可逆语法是拉取请求的结果 20018.拉取请求还更新了 Edge Rails 的 Rails 指南.

Reversible syntax for change_column_default is the result of pull request 20018. The pull request also updated the Rails guides for Edge Rails.

来自 activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb:

-      def change_column_default(table_name, column_name, default)
+      # Passing a hash containing +:from+ and +:to+ will make this change
+      # reversible in migration:
+      #
+      #   change_column_default(:posts, :state, from: nil, to: "draft")
+      #
+      def change_column_default(table_name, column_name, default_or_changes)

拉取请求是在 2015 年 6 月 27 日提出的,比截至 2015 年 8 月 1 日发布的任何版本的 Rails 都更新.

The pull request was made June 27, 2015, which is more recent than any version of Rails released as of August 1, 2015.

Rails 4.2.3 迁移 的文档反映了可逆的事实语法尚不可用:

The documentation for migration for Rails 4.2.3 reflects the fact that reversible syntax is not yet available:

change_column_default :products, :approved, false

这篇关于由于 Rails 中没有任何默认值,change_column_default 的可逆迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆