How do set default value for ActiveRecord fields?

Everytime a new record object is created i.e. Record.new, i want certain
fields to be the same.

Any idea how to do this?
Thanks
Chris

On Aug 01, 2006, at 12:26 pm, Chris wrote:

Everytime a new record object is created i.e. Record.new, i want
certain
fields to be the same.

Any idea how to do this?
Thanks
Chris

Chris,

You want to set defaults in the database columns. The easiest way to
do this is to build your database with Rails migrations: http://
wiki.rubyonrails.org/rails/pages/UnderstandingMigrations and
use :default => XXX in your column definitions.

Ashley

On Tuesday, August 01, 2006, at 1:26 PM, Chris wrote:

Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails

Easiest way would be to define :default=>some_value in the migration for
each column

t.column “title”, :string, :default=>‘test’

_Kevin
www.sciwerks.com

Chris wrote:

So when you create a new activerecord instance (before you save it) does
it look to see what the default value is from the schema?

I want the default value to be assigned upon creation of the object,
i.e. Record.new, and not when it gets saved.

Set the default value in the controller.

eg.
def firstpage
Tablename.column = default_value
end

I havn’t looked at ruby for a while but its something like that.
Does this help?

So when you create a new activerecord instance (before you save it) does
it look to see what the default value is from the schema?

I want the default value to be assigned upon creation of the object,
i.e. Record.new, and not when it gets saved.

On 2006-08-01, at 10:02 , Simon wrote:

Chris wrote:

So when you create a new activerecord instance (before you save
it) does
it look to see what the default value is from the schema?

It does. That’s also why you can’t have expressions as defaults (eg.
NOW()), just literals.

I want the default value to be assigned upon creation of the object,
i.e. Record.new, and not when it gets saved.

Yep. Rails will look it up, it’ll be set at instantiation.

Set the default value in the controller.

Bad idea. Let the model handle it.

I’m thinking about writing a plugin that initializes default values.
It’s useful when you have more complex defaults, e.g. with
inheritance, that each descendant model may have a different default
for the same field. Sintax would be something like

class Post < AR…
defaults :title => ‘(untitled)’, :status => ‘unpublished’,
:whatever => lambda { |record| … some dynamic magic … }
end

You can also do similar just by overriding the accessors.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs