使用ruby和active_record保存时的DEPRECATION WARNING

我是ruby的新手并且编写了一个需要将消息写入数据库日志的小脚本。

我使用ruby 1.9.3与active_record但没有rails。 所有select语句都可以正常工作,但我写入日志函数返回以下错误:

DEPRECATION WARNING: You're trying to create an attribute `ID'. Writing arbitrary attributes on a model is deprecated. Please just use `attr_writer` etc. 

我的模型看起来像那样

 class ActLog < ActiveRecord::Base self.table_name = "ActLog" self.primary_key = "ID" end 

和我的日志function:

 def log(level, message) level.upcase! line = ActLog.new line.level = level line.message = message line.module = 'script' line.date = Time.new.strftime("%Y-%m-%d %H:%M:%S") line.save end 

ID字段是int auto_increment。

执行期间将多次调用日志函数。 这是写入日志的最佳方式,为什么会出现弃用警告?

我检查了API ,你正在使用的方法是最新的。 我想你可能需要attr_accessor

 class ActLog < ActiveRecord::Base attr_accessor :id, :level, :message, :module, :date self.table_name = "ActLog" self.primary_key = "ID" end def log(level, message) attr = { :level => level.upcase!, :message => message, :module => 'script', :date => Time.new.strftime("%Y-%m-%d %H:%M:%S") } ActLog.new(attr).save! end 

我认为你的课应该如下:

 class ActLog < ActiveRecord::Base self.primary_key = 'ID' self.table_name = 'ActLog' end 

出于好奇,为什么非标准的名字?