Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert timestamp into rails database-column

I just started with RoR and have a question: How can I insert the current timestamp (or any type of time) into the model? Below you see the log function create.

def create
    @log = Log.new(params[:log])

    respond_to do |format|
      if @log.save
        format.html { redirect_to @log, notice: 'Log was successfully created.' }
        format.json { render json: @log, status: :created, location: @log }
      else
        format.html { render action: "new" }
        format.json { render json: @log.errors, status: :unprocessable_entity }
      end
    end
  end
like image 816
zyrup Avatar asked Mar 15 '13 00:03

zyrup


1 Answers

The Rails model generator automatically creates created_at and updated_at datetime fields in the database for you. These fields are automatically updated when a record is created or updated respectively.

If you want to manually create a timestamp, add a datetime column (e.g. timestamp_field) to the database and use a before_save callback in your model.

class Log < ActiveRecord::Base
  before_save :generate_timestamp

  def generate_timestamp
    self.timestamp_field = DateTime.now
  end
end
like image 181
Richard Brown Avatar answered Sep 28 '22 10:09

Richard Brown