Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 558
chell Avatar asked Jul 27 '11 09:07

chell


1 Answers

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
like image 142
dexter Avatar answered Nov 09 '22 19:11

dexter