Ruby on rails 如何将时间戳插入rails数据库列
我刚从RoR开始,有一个问题:如何将当前时间戳(或任何类型的时间)插入到模型中?下面是日志函数createRuby on rails 如何将时间戳插入rails数据库列,ruby-on-rails,Ruby On Rails,我刚从RoR开始,有一个问题:如何将当前时间戳(或任何类型的时间)插入到模型中?下面是日志函数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 { r
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
字段。当分别创建或更新记录时,这些字段将自动更新
如果要手动创建时间戳,请向数据库中添加日期时间列(例如,时间戳字段
),并在模型中保存前使用回调
class Log < ActiveRecord::Base
before_save :generate_timestamp
def generate_timestamp
self.timestamp_field = DateTime.now
end
end
类日志
使用rails生成器,例如rails生成模型日志
rails会自动为您创建两个时间戳字段
created_at
和updated_at
这两个字段都将在您创建新记录时由Rails填充。新建然后保存该记录或日志。创建仅当您更新记录的属性或使用该方法时,updated_at
字段才会更新触摸模型实例上的
现在,如果您想创建另一个具有时间戳类型的字段,您可以进行迁移,向您的模型中添加一列,如下所示
rails generate migration add_some_timestamp_field_to_logs my_timestamp_field:timestamp
这将生成一个迁移,该迁移将添加一个名为my\u timestamp\u field
的列,其类型为timestamp
,就像在
创建的和在
更新的一样,您是否使用rails生成器创建了模型?但是我会插入时间戳。您不需要编写self.timestamp\u字段=DateTime。现在
?@DonKirkby我相信是这样的,因为timestamp\u字段
目前被定义为局部变量,据我所知,ActiveRecord不假设变量名与类属性匹配。因此,您需要按照您的建议使用self
作为前缀,或者使用@
作为实例变量。再说一次,我从来没有遇到过这种情况,只是猜测而已。