Agile Web Development

Build it. Launch it. Love it.

Default Value

Sets up accessors returning a provided value for one or more fields. If the values of the fields aren’t set upon saving the record, the fields are set to the default value provided. Fields may be given as an array of symbols referring to fields or a single symbol referring to a single field. Setting a field to nil has the effect of setting the field to its default value.

For example:

  class Mixture < ActiveRecord::Base
    serialize :color
    default_value :color, [255, 0, 0]
  end

  m = Mixture.new
  m.color # => [255,0,0]

  another = Mixture.new(:color => [0,255,0])
  another.color # => [0,255,0]

  another.color = nil
  another.color # => [255,0,0]

And with multiple fields:

  class Something
    default_value [:foo, :bar], 1
  end

  s = Something.new
  s.foo # => 1
  s.bar # => 1

The value may also be a symbol or proc object. The result of calling the proc or the method referred to by the symbol is used as the value.

  class Genre < ActiveRecord::Base
    has_many :movies
  end

  class Movie < ActiveRecord::Base
    belongs_to :genre
    default_value :rating, Proc.new {|m| m.genre.default_rating }
  end

  sci_fi = Genre.create(:title => "Science Fiction", :default_rating => "PG-13")

  spaceballs = sci_fi.movies.create(:title => "Spaceballs")
  spaceballs.rating # => PG-13 (though it should actually be PG)

Vitals

Repository http://mdaines.com/svn/plugins/default_value/trunk/
License
Rating (6 votes)
Owner Michael Daines
Created 7 June 2006

Comments

  • Avatar
    Alex Egg
    28 August 2007

    I would wonder why this functionality isn't already build into rails...

  • Avatar
    Alex Egg
    28 August 2007

    the svn link is broken...

  • matt s
    8 September 2007

    wtf! I want to be able to do this, maybe I can do it in migrations...

  • Michael Schuerig
    4 December 2007

    Wouldn't it be just as easy to use database defaults? They can be defined in migrations.

Add a comment