0

I have a table column - valid_to, which should represent a date: 30 days from the time the entry was saved into database. But how can I do such a thing in model? E.g. in controller I can do such thing this way:

@baby = baby.create(baby_params.
        merge( :valid_to => DateTime.current + 30 )

In view I can use hidden field in the form:

<%= f.hidden_field :valid_to => DateTime.current + 30 %>

so is there a way to do such a thing in model? I tried defining self.valid_to before_validation but for no avail: in irb my valid_to column is just nil. To add: I store it as datetime not string.

UPDATE

solution in the end was:

before_validation :set_valid_to, :on => :create

def set_valid_to
  self[:valid_to] = 30.days.from_now
end

and lived this thing in module, but that's another story...

  • possible duplicate of http://stackoverflow.com/questions/4654457/how-to-add-10-days-to-current-time-in-rails – Brad Dec 17 '16 at 03:10
  • @Brad, sorry if I was way-out in my wording, but by mentioning irb, I meant observing my db entries in console, calling Baby.all, not calculating. That question as it's answers didn't help solve my problem. – That's me - who else Dec 17 '16 at 03:34

2 Answers2

0

The below should work if you only want it done on initial record creation. If you want it updated every time it's saved use before_save instead of before_create.

class Baby < ActiveRecord::Base
  before_create :set_valid_to

  private

  def set_valid_to
    self.valid_to = 30.days.from_now
  end
end
Philip Hallstrom
  • 19,673
  • 2
  • 42
  • 46
0

in irb:

@baby = baby.create
@baby.valid_to = Time.now + 30.days
@baby.save
Brad
  • 8,044
  • 10
  • 39
  • 50