Denis Papushaev Denis Papushaev - 6 months ago 39
Ruby Question

Default values for models in rails

Is it better to set default value in migration or in callback? It's difficult to delete (or set another) default value in migration, but in model it one more piece of code


Defining defaults in your migration has some disadvantages as well. This will not work when you just call

I prefer to write an after_initialize callback, which lets me set default attributes:

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?