在迁移或回调中设置默认值更好吗?在迁移过程中很难删除(或设置另一个)默认值,但是在模型中要多编写一段代码
在迁移中定义默认值也有一些缺点。当您仅致电时,这将不起作用Model.new
。
我更喜欢编写一个after_initialize
回调,该回调使我可以设置默认属性:
class Model < ActiveRecord::Base
after_initialize :set_defaults, unless: :persisted?
# The set_defaults will only work if the object is new
def set_defaults
self.attribute ||= 'some value'
self.bool_field = true if self.bool_field.nil?
end
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句