【问题标题】:Rails migration set current date as default valueRails 迁移将当前日期设置为默认值
【发布时间】:2012-02-01 03:08:54
【问题描述】:

我在表格中有一个日期列:

create_table "test", :force => true do |t|
     t.date  "day"
end

我想将当前日期设置为此列的默认值。 我尝试如下:

create_table "test", :force => true do |t|
     t.date  "day", :default => Date.today
end

但默认始终是 2 月 1 日,所以如果我明天创建新记录,那一天仍然是 2 月 1 日(预计是 2 月 2 日)

感谢您的回复!

注意:我在 rails 3 中使用 sqlite

【问题讨论】:

    标签: ruby-on-rails migration


    【解决方案1】:

    您可以为动态初始化程序传递一个 lambda。

    create_table "test", :force => true do |t|
      t.date  "day", default: -> { 'CURRENT_DATE' }
    end
    

    旧答案

    Rails 不支持迁移中的动态默认值。 迁移执行期间的任何内容都将在数据库级别设置,并保持这种状态,直到迁移被回滚、覆盖或重置。但是您可以轻松地在模型级别添加动态默认值,因为它是在运行时评估的。

    1) 使用after_initialize回调设置默认值

    class Test
      def after_initialize
        self.day ||= Date.today if new_record?
      end
    end
    

    仅当您需要在初始化之后和在保存记录之前访问属性时才使用此方法。这种方法在加载查询结果时有额外的处理成本,因为必须为每个结果对象执行块。

    2) 使用before_create回调设置默认值

    class Test
      before_create do
        self.day = Date.today unless self.day
      end
    end
    

    此回调由您的模型上的 create 调用触发。 There are many more callbacks。例如,在createupdate 上设置验证前的日期。

    class Test
      before_validation on: [:create, :update] do
        self.day = Date.today
      end
    end
    

    3) 使用default_value_for gem

    class Test
      default_value_for :day do
        Date.today
      end
    end
    

    【讨论】:

      【解决方案2】:

      您可以设置从 Rails 5 迁移的默认日期

      create_table :posts do |t|
        t.datetime :published_at, default: -> { 'NOW()' }
      end
      

      这是来自 rails repo 的 link

      【讨论】:

        【解决方案3】:

        刚刚完成 Harish Shetty 的回答。
        对于 Rails 应用程序,您必须使用以下语法:

          class Test < ActiveRecord::Base
            after_initialize do |test|
              test.day ||= Date.today if new_record?
            end
          end
        

        【讨论】:

          【解决方案4】:

          不要认为您可以在迁移中做到这一点。但是,Rails 已经在新模型迁移中添加了一个 created_at 字段,可以满足您的需求。如果您需要自己的属性做同样的事情,只需使用 before_save 或 before_validate 来设置它(如果它是 nil)。

          【讨论】:

            【解决方案5】:

            我知道 Mysql 不接受默认的列类型作为函数。我假设 sqlite 是一样的。

            http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2018-07-25
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2014-05-06
              • 1970-01-01
              • 2018-11-23
              • 1970-01-01
              相关资源
              最近更新 更多