Notinlist
Notinlist

Reputation: 16640

Offer current date in Rails

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.

Upvotes: 1

Views: 341

Answers (3)

Steve Weet
Steve Weet

Reputation: 28392

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

Upvotes: 2

Swanand
Swanand

Reputation: 12426

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

Upvotes: 2

Slobodan Kovacevic
Slobodan Kovacevic

Reputation: 6888

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

Upvotes: 1

Related Questions