How to insert timestamp into rails database-column
ruby-on-rails
Solution
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
Problem
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 ```