Home > Software design >  Updating one column with a value of another if nil?
Updating one column with a value of another if nil?

Time:11-15

There is a column within my car table called 'manufacture_date' and another column called 'registration_date'. When a user updates a record via the update action in the controller. Manufacture date can currently be left nil. However, if it is nil I want the value of the registration_date(which cannot be left nil) to be copied into the manufacture date. I'm really not to sure how to accomplish this. Note: I do not want to rescue or allow a nil value. I need it if nil, to contain the same date as the registration_date.

Manufacturer date code ran when user updates the record in a form.

  new_manufacture_date = Date.parse(params[:car][:manufacture_date]) 

CodePudding user response:

The easiest way would be a before_validation callback in your model like this:

before_validation :set_manufacture_date_fallback

private

def set_manufacture_date_fallback
  self.manufacture_date ||= registration_date
end

Which would assign the value of registration_date to manufacture_date when manufacture_date is not set yet right before validating and saving the record into the database.

  • Related