Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 046569/6749404 to your computer and use it in GitHub Desktop.
Save 046569/6749404 to your computer and use it in GitHub Desktop.

所有的坑都来自于 无知 ,这次也不例外,我又掉坑里了...

先来看段代码:

  def change
    add_column :servers, :vip_date, :date, :default => Date.today
  end

这是一个很常见的迁移任务,新增一栏,设置默认值.执行迁移也毫无警告,看起来一切都那么美好.而真相其实是这样的:

假设今天是9月9日:

Server.new.vip_date  #=> Sun, 09 Sep 2013

嗯,看起来很完美.可过了一天你再试试?

Server.new.vip_date  #=> Sun, 09 Sep 2013

见鬼,怎么还是相同的日期?难道Date.today秀逗了?

表象可能有很多种,而真相只有一个:

Active Record Migrations并不支持 动态默认值,你应该在回调中处理,比如after_initialize.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment