简体   繁体   中英

ruby on rails - add end_time upon record creation

I'm trying to have a record with ends_at column which is suppose to have the created_at value with 5 minutes added to it for instance:

Class Post < ApplicationRecord
  after_create :set_end_time

  private
    def set_end_time
      self.ends_at = self.created_at + 5.minutes
    end
end

this saves the ends_at column as a null in the database

You fire after_create hook. It gets triggered after Rails calls SQL INSERT command. So you setup ends_at already when object was saved to the database and it will not be saved again. Object with initialized ends_at not going anywhere and then just get cleared from the memory.

Replace your hook with before_create and it should do the trick for you.

You forgot to save the record

def set_end_time
  self.ends_at = self.created_at + 5.minutes
  save
end

One hard way to do it would be to set a default value when a row is created if the migration for exemple change_column_default :posts, :end_time, "current_timestamp + (5 ||' minutes')::interval" if you use postgres for exemple.

But only do that if you are sure that this is not going to change soon. If it is, then setting a before_create hook with a custom setter is the way to go (Just be sure that your field is of datetime type)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM