简体   繁体   English

Rails ActiveRecord,在Postgres中插入默认字段值

[英]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_timestampDEFAULT 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.

相关问题 Rails 5,Postgres,ActiveRecord-如何将函数值包含在模型字段中 - Rails 5, Postgres, ActiveRecord - how to include function value as model field Rails 3 ActiveRecord插入无法插入空值 - Rails 3 ActiveRecord Insert Cannot Insert Value Null 基于列值的Rails,Postgres,ActiveRecord查询postgres - Rails, Postgres, ActiveRecord query postgres based on columns value Rails:使用ActiveRecord摆脱默认值吗? - Rails: Get rid of default value using ActiveRecord? Rails 5 - 间歇性错误 - ActiveRecord::NotNullViolation(Mysql2::Error:字段“created_at”没有默认值 - Rails 5 - Intermittent Error - ActiveRecord::NotNullViolation (Mysql2::Error: Field 'created_at' doesn't have a default value Rails - ActiveRecord - 触发更改字段值的邮件 - Rails - ActiveRecord - Trigger mail on change of a field value Rails Activerecord基于字段值的最后5条记录 - Rails Activerecord last 5 records based on field value 如何使用ActiveRecord访问Postgres列的默认值? - How can I access a Postgres column default value using ActiveRecord? 通过Rails Activerecord在Postgres HSTORE中保存第一个键/值对 - Saving first key/value pair in Postgres HSTORE via Rails Activerecord 未设置默认布尔值Rails 4 Postgres - Default boolean value not being set Rails 4 Postgres
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM