views:

40

answers:

3

I want to offer the current date to the user when a new record is created and I want to allow him to edit the offered date. For example I write a bug tracking system and I have a date_of_detection field. 99% of the time it is good if it is the current date, but for the sake of the 1% the user should be allowed to edit it and set any earlier date.

I'm interested in any hack, but at the end I would like to have a nice way to do it.

+1  A: 

When you create a new bug in controller just set the value of date_of_detection. Something like:

@bug = Bug.new(:date_of_detection => Date.today)

# or something like this

@bug = Bug.new
@bug.date_of_detection = Date.today
Slobodan Kovacevic
I have *Model, *Controller, *Helper, and migrations and other stuff. There is no mention of `Bug.new`, because it is hidden in the framework. There is a hooking possibility somewhere - I think - which I cannot find.
Notinlist
+1  A: 

In addition to Slobodan's answer, if you end up doing this in many places, and just want to do it one place, you can do it this way:

class Bug < ActiveRecord::Base
  def initialize
    attributes = {:date_of_detection => Date.today}
    super attributes
  end
end

>> Bug.new.date_of_detection
=> Thu, 12 Aug 2010
Swanand
Be very careful when over-riding ActiveRecord initializers. This can break things in very subtle ways and is generally not recommended. If possible use an after_initialize callback.
Steve Weet
@Steve: Agreed about the over-riding behavior. However, does it work on nil columns? i.e. columns which have been purposefully saved with null entries? I have found in the past that it doesn't, I must confess I haven't played around with it as much.
Swanand
@Swanand. There is an after_find initializer as well that you can implement for that. The problem with overriding initialize is that some ActiveRecord mechanisms use allocate instead of new to instantiate instances and in those cases the initializer is not run.
Steve Weet
+2  A: 

Whilst Swanands solution will probably work overriding initialize for activerecord objects is not recommended and can cause some hard to find bugs.

The after_initialize callback is there for just this purpose.

class Bug < ActiveRecord::Base

  def after_initialize
    self.date_of_detection = Date.today if self.date_of_detection.nil?
  end
end
Steve Weet