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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With