【问题标题】:When using change_column_default on a column with no default, what should be the 'from' value?在没有默认值的列上使用 change_column_default 时,'from' 值应该是什么?
【发布时间】:2017-03-08 06:54:14
【问题描述】:

这是我的创建表迁移。请注意,我没有提供price 的默认值。

class CreateProducts < ActiveRecord::Migration[5.0]
  def change
    create_table :products do |t|
      t.string :name
      t.decimal :price, precision: 8, scale: 2

      t.timestamps
    end
  end
end

现在我想设置一个默认值。根据the Migration guide,我应该提供from 以使其可逆。我应该提供什么价值?

class ChangeProductsPriceDefault < ActiveRecord::Migration[5.0]
  def change
    change_column_default :products, :price, from: 'WHAT_TO_WRITE_HERE?', to: 0
  end
end

【问题讨论】:

  • 写自:nil @wit。

标签: ruby-on-rails rails-activerecord rails-migrations


【解决方案1】:

“No default”表示默认为NULL,所以:

change_column_default :products, :price, from: nil, to: 0

关于默认为 nil 的描述:http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-change_column_default

【讨论】:

  • 我很想使用null。你能告诉我更多为什么是nil,而不是null吗?
  • null 仅在 SQL 中有效,但 nil 仅在 ruby​​ 中有效。两者的意思几乎相同——没有价值。
猜你喜欢
  • 2015-08-25
  • 2015-10-11
  • 1970-01-01
  • 1970-01-01
  • 2016-01-04
  • 2011-12-11
  • 1970-01-01
  • 1970-01-01
  • 2018-05-21
相关资源
最近更新 更多