Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #5445 (reopened defect)

Opened 2 years ago

Last modified 2 years ago

default column values containing functions do not work correctly

Reported by: dan@chak.org Assigned to: David
Priority: normal Milestone: 1.2.7
Component: ActiveRecord Version: 1.0.0
Severity: normal Keywords:
Cc:

Description

If the database table backing your model class contains defaults that are meant to be evaluated at insert time (e.g., the now() function in Postgres for a created_at column), they will not work as expected.

attributes_from_column_definitions, invoked by ActiveRecord::Base.initialize, sets columns to column.default, which must be evaluated when it is initially set, rather than each time it is called.

The following illustrates: notice that the default time, which is defined in the schema as 'now()' is always the same:

>> UserResponse.columns.find{|foo| foo.name == 'created_at'}
=> #<ActiveRecord::ConnectionAdapters::Column:0x249b4ec @primary=false, @default=Tue Jun 20 10:35:17 EDT 2006, @type=:datetime, @number=false, @limit=nil, @text=false, @name="created_at", @null=false>
>> UserResponse.columns.find{|foo| foo.name == 'created_at'}
=> #<ActiveRecord::ConnectionAdapters::Column:0x249b4ec @primary=false, @default=Tue Jun 20 10:35:17 EDT 2006, @type=:datetime, @number=false, @limit=nil, @text=false, @name="created_at", @null=false>
>> UserResponse.columns.find{|foo| foo.name == 'created_at'}
=> #<ActiveRecord::ConnectionAdapters::Column:0x249b4ec @primary=false, @default=Tue Jun 20 10:35:17 EDT 2006, @type=:datetime, @number=false, @limit=nil, @text=false, @name="created_at", @null=false>

The way to get around this particular problem is to not have defaults for the created_at column, since ActiveRecord will actually do the right thing if no default is provided. However, for other columns this can be a big problem if the default is actually intended to come from a stored procedure.

Change History

06/29/06 21:25:36 changed by anonymous

  • status changed from new to closed.
  • resolution set to duplicate.

This was also addressed in #5112 I just noticed. So I put the patch there and I'm closing this ticket.

06/29/06 23:54:15 changed by dan@chak.org

  • status changed from closed to reopened.
  • resolution deleted.

The patch in #5112, which has to do with defaults for _validation_, is unrelated to this ticket, which has to do with defaults for a column specified in a database schema.

This has nothing to do with validation. Rather, database defaults that are defined via a stored procedure get "stuck" to their first value as evaluated by Rails.