Denis Papushaev Denis Papushaev - 1 year ago 120
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

Answer Source

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?
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download