[英]Rails ActiveRecord, INSERT default field value in Postgres
This should be an easy one, but I've googled a fair bit. 这应该很容易,但是我已经在Google上搜索了很多。
I am trying to create a database log for my rails app. 我正在尝试为Rails应用程序创建数据库日志。 The log is a postgres table which has a timestamp
field, which I have given a DEFAULT
of current_timestamp
. 日志是一个postgres表,其中包含一个timestamp
字段,我已将它指定为current_timestamp
的DEFAULT
。 This works perfectly in raw SQL, if I leave the timestamp
field out of my INSERT
query, it gets the current timestamp correctly. 如果在我的INSERT
查询中没有添加timestamp
字段,则可以在原始SQL中很好地工作,它可以正确获取当前时间戳。
In rails I have; 我在铁轨上
entry = LogTable.new :fieldA => 'valA', :fieldB => 'valB'
entry.save
(LogTable extends ActiveRecord::Base) (LogTable扩展了ActiveRecord :: Base)
Which results in an INSERT
query that contains all fields, including the timestamp
field set to NULL
, which is not allowed by the database so it errors. 这将导致INSERT
查询包含所有字段,包括timestamp
字段设置为NULL
,这是数据库不允许的,因此会出错。
I have tried setting :timestamp => 'current_timestamp'
and :timestamp => 'DEFAULT'
but all end up trying to set it to NULL
. 我曾尝试设置:timestamp => 'current_timestamp'
和:timestamp => 'DEFAULT'
但是最终都试图将其设置为NULL
。
Is your current_timestamp just the current date/time? 您的current_timestamp仅是当前日期/时间吗? If so, you can stay simple and do something like: 如果是这样,您可以保持简单并执行以下操作:
entry = LogTable.new :fieldA => 'valA', :fieldB => 'valB', :timestamp => Time.now
If it's something more complex and you really want to use DB-side defaults, this page might help: http://drawohara.com/post/6677354/rails-activerecord-default-values . 如果问题更加复杂,并且您确实想使用数据库端默认值,则此页面可能会有所帮助: http : //drawohara.com/post/6677354/rails-activerecord-default-values 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.