2012-02-01 115 views
12

我有一列日期表:Rails的迁移设置当前日期作为缺省值

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日)

感谢响应!

注:我使用的轨道3

回答

22

Rails不支持动态迁移的默认值。 无论您的迁移在执行过程中会在数据库级别设置,并保持这种状态,直到迁移回滚,重写或重置。但是,您可以轻松地在模型级别添加动态默认值,因为它在运行时进行评估。使用after_initialize回调

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

使用此方法仅当您需要初始化和后访问属性之前保存记录

1)设置的默认值。此方法在加载查询结果时会有额外的处理成本,因为必须为每个结果对象执行块。使用before_create回调

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

2)设置的默认值这个回调是由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宝石

class Test 
    default_value_for :day do 
    Date.today 
    end 
end 
+0

非常感谢你,它的工作原理 – banhbaochay 2012-02-01 09:24:45

1

源码不要以为你能做到这一点的迁移。但是,Rails已经将created_at字段添加到了新模型迁移中,并且可以实现您想要的功能。如果你需要你自己的属性做同样的事情,只需使用before_save或before_validate来设置它,如果它是零。

3

刚刚完成哈里什谢蒂的答案。
对于Rails应用程序,您必须使用此语法:

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