How to set default values in your model
Published almost 8 years ago

In lights of recent discussion at rails core mailing list – I’m posting a code snippet showing how to set default values for your model without possibly screwing up.

class Item < ActiveRecord::Base  
  def initialize_with_defaults(attrs = nil, &block)
    initialize_without_defaults(attrs) do
      setter = lambda { |key, value| self.send("#{key.to_s}=", value) unless !attrs.nil? && }'scheduler_type', 'hotseat')
      yield self if block_given?
  alias_method_chain :initialize, :defaults

This will work even when you supply a block to – and it’s helpful in cases where you want to override default values.