Ayrad
Ayrad

Reputation: 4056

add an expiration date to to a rails model saves nil instead of date

I am trying to make my expiration date populate in a rails app:

I added my column like this:

class AddExpirationToPost < ActiveRecord::Migration
  def change
    add_column :posts, :expiration, :date
  end
end

In my model I added :

  after_create :set_expiration_date

def set_expiration_date
  self.expiration =  Date.today + 30.days
end

but when I create the post, it saves nil in expiration field instead of the date.

Upvotes: 0

Views: 2112

Answers (3)

Matt
Matt

Reputation: 14038

You need to either set the value before saving, or save the value after setting it. I'd recommend the former:

before_create :set_expiration_date 

def set_expiration_date
  self.expiration =  Date.today + 30.days
end

There are a lot of callbacks you can tie this method to, after_create happens after the row is saved to the database, so your line is ineffective.

Upvotes: 0

fmendez
fmendez

Reputation: 7338

For this particular scenario, you should be using: before_save set_expiration_date, that or just called save again (that would be redundant tho):

def set_expiration_date
  self.expiration =  Date.today + 30.days
  save
end

The one you're currently using is called after Base.save on new objects that haven’t been saved yet (no record exists).

after_create api doc

Upvotes: 1

Mori
Mori

Reputation: 27779

By using after_create you're setting that value after it has been saved in the database. You can use before_create instead.

Upvotes: 1

Related Questions