如何将时间戳插入到 rails 数据库列中 [英] How to insert timestamp into rails database-column
问题描述
我刚开始使用 RoR,有一个问题:如何将当前时间戳(或任何类型的时间)插入模型中?下面你会看到日志函数创建.
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
推荐答案
Rails 模型生成器自动创建 created_at
和 updated_at
datetime
字段数据库给你.这些字段会在分别创建或更新记录时自动更新.
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.
如果您想手动创建时间戳,请将日期时间列(例如 timestamp_field
)添加到数据库并在模型中使用 before_save
回调.
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
这篇关于如何将时间戳插入到 rails 数据库列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!