How to insert a timestamp into a rails database column

I just started with RoR and asked the question: how can I insert the current timestamp (or any type of time) into the model? Below you see how the log function is created.

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
+5
source share
2 answers

Rails model generator automatically creates the field created_atand updated_at datetimein the database for you. These fields are automatically updated when a record is created or updated accordingly.

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

class Log < ActiveRecord::Base
  before_save :generate_timestamp

  def generate_timestamp
    self.timestamp_field = DateTime.now
  end
end
+18
source

, , rails generate model Log rails .

created_at updated_at Rails , Log.new, save Log.create updated_at , touch .

, timestamp, , , ,

rails generate migration add_some_timestamp_field_to_logs my_timestamp_field:timestamp

, my_timestamp_field timestamp, created_at updated_at

+2

All Articles