在RoR 3.1中,"validates"仍然没有在模型中设置默认值的方法。或者说有吗?如果没有,那么设置默认值的最佳方式是什么?
class Abc
before_save :set_default
protected
def set_default
self.xyz = "default" unless self.xyz
end
end
self.up do
update_column :table_name,:column_name,:default=>your default value
end
这对我来说很有效
class WorkLogEntry < ActiveRecord::Base
after_initialize do
self.work_done_on ||= Time.zone.today
end
...
end
Time.zone.today
获取今天的日期,该方法会考虑到时区。 - Joshua Pinter当模型使用空字段参数获取表单参数时,该字段的参数将具有nil参数。因此,如果您初始化相同的@foo ='bar'并且用户发送带有空参数[:foo]的表单,则Model.create(params [:model])将具有foo => nil。
您可以通过迁移在数据库结构中设置默认参数:
create_table:comments do |t|
t.text:comment,:default =>'bar'
end
self.xyz ||= "default"
吗? - Hopstream