Rails中模型的默认值

丹尼斯·帕普谢夫(Denis Papushaev)

在迁移或回调中设置默认值更好吗?在迁移过程中很难删除(或设置另一个)默认值,但是在模型中要多编写一段代码

沙威·艾哈迈德(Sharvy Ahmed)

在迁移中定义默认值也有一些缺点。当您仅致电时,这将不起作用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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章