Plugins - Default Value

StarAdd to favorites

Default value plugin for Rails

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)

Michael Daines

http://mdaines.com/svn/plugins/default_value/trunk/

  • Currently 4.0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Model

Tags

Comments

Add a comment
Michael Schuerig 4 Dec 2007

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

matt s 8 Sep 2007

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

Alex Egg 28 Aug 2007

the svn link is broken...

Alex Egg 28 Aug 2007

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

Search Plugins

Query syntax

Plugins by Category

Sponsors

Rails Kits: Get Code. Get Moving.

Have a comment?