chell
chell

Reputation: 7866

change year for a date in Rails

I have a form that gets the birthday of a user.

I want to take the birthday and store it in another attribute but take the current year.

I do this in a call back

Model board

before_save :set_delivery_date

def set_delivery_date

self.delivery_date = self.birthday
self.delivery_date.change(:year => Time.now.year)
end

The birthday is 1920-07-27

This does not seem to change the date.

Anyone know how to do this?

Update

The following works I can see the new date in the database:

 self.deliver_on = self.birthday.change(:year => Time.now.year)

However when I try to do rspec tests or I try it in the console it produces the following error:

ArgumentError: invalid date

anyone know why this is happening?

Upvotes: 8

Views: 6770

Answers (3)

Mario Uher
Mario Uher

Reputation: 12397

ActiveRecord's Dirty Object feature does not know about your changes. There are two ways to fix this:

def set_delivery_date
  self.delivery_date = self.birthday
  self.delivery_date = self.delivery_date.change(:year => Time.now.year)

  # Shorter
  self.delivery_date = self.birthday.change(:year => Time.now.year)
end

or tell ActiveRecord about your changes:

def set_delivery_date
  self.delivery_date = self.birthday
  self.delivery_date_will_change!
  self.delivery_date.change(:year => Time.now.year)
end

Upvotes: 2

dexter
dexter

Reputation: 13593

The change method returns a new date instance with one or more elements changed.

Try this:

def set_delivery_date
   self.delivery_date = self.birthday
   self.delivery_date = self.delivery_date.change(:year => Time.now.year)
end

Upvotes: 14

nathanvda
nathanvda

Reputation: 50057

Your code seems correct. So I would check reasons why your object is not saved:

  • the object is not valid? E.g. object.valid? returns false. Validation checks happen before the save.
  • you are not saving?

Upvotes: 0

Related Questions