What is the best way to set default values in ActiveRecord?

Posted by ryw on Stack Overflow See other posts from Stack Overflow or by ryw
Published on 2008-11-30T06:27:29Z Indexed on 2010/04/24 18:23 UTC
Read the original article Hit count: 205

Filed under:
|
|

What is the best way to set default value in ActiveRecord?

I see a post from Pratik that describes an ugly, complicated chunk of code: http://m.onkey.org/2007/7/24/how-to-set-default-values-in-your-model

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? && attrs.keys.map(&:to_s).include?(key.to_s) }
      setter.call('scheduler_type', 'hotseat')
      yield self if block_given?
    end
  end
  alias_method_chain :initialize, :defaults
end

YUCK!

I have seen the following examples googling around:

  def initialize 
    super
    self.status = ACTIVE unless self.status
  end

and

  def after_initialize 
    return unless new_record?
    self.status = ACTIVE
  end

I've also seen people put it in their migration, but I'd rather see it defined in the model code.

What's the best way to set default value for fields in ActiveRecord model?

© Stack Overflow or respective owner

Related posts about activerecord

Related posts about ruby