我有一些属性需要有默认值。我已经设置了迁移以在数据库中设置默认值,如下所示:
class AddDefaultsToModel < ActiveRecord::Migration[5.2]
def change
change_column :posts, :post_type, :string, default: 'draft'
change_column :posts, :date_time, :datetime, default: -> { 'CURRENT_TIMESTAMP' }
end
end
Run Code Online (Sandbox Code Playgroud)
直接添加到数据库时,默认值效果很好。但是,如果我在 Rails 中构建一个新模型,一个属性会按预期工作,而另一个则不会:
post = Post.new
post.post_type # draft (as expected)
post.date_time # nil (expecting the current date and time)
Run Code Online (Sandbox Code Playgroud)
这种行为是故意的吗?我是否也必须在模型中设置默认值?为什么Post#post_type有效但无效Post#date_time?
我有一个 PostGres 9.4 数据库。我想将 DATETIME 列的默认列类型更改为创建记录的时间。我认为这是正确的方法,因为这是我的 Rails 迁移
class ChangeDefaultValueForStratumWorkerSubmissions < ActiveRecord::Migration[5.1]
def change
change_column_default(:stratum_worker_submissions, :created_at, 'NOW')
end
end
Run Code Online (Sandbox Code Playgroud)
但是当我查看数据库时,默认时间戳显示为我运行迁移的时间,而不是我想要的表达式。我如何编写一个可以实现我想要的迁移?
Column | Type | Modifiers
-------------------+-----------------------------+----------------------------------------------------------------------------
id | integer | not null default nextval('stratum_worker_submissions_id_seq'::regclass)
stratum_worker_id | integer |
created_at | timestamp without time zone | not null default '2018-04-04 19:46:22.781613'::timestamp without time zone
Run Code Online (Sandbox Code Playgroud) postgresql ruby-on-rails default-value rails-migrations ruby-on-rails-5
我需要将特定的 Postgres 序列分配给表的 ID 字段。在模型中,我尝试定义以下对 Posgres 没有影响的设置:
类 MyObject < ActiveRecord::Base
self.sequence_name = "global_seq"
通常,ActiveRecord 迁移中的表定义以
create_table "objects", id: :serial, force: :cascade do |t|
Run Code Online (Sandbox Code Playgroud)
它生成列默认值的 Postgres 定义为
default nextval('objects_id_seq'::regclass)
Run Code Online (Sandbox Code Playgroud)
如何在迁移中指定 nextval() 函数应该依赖于另一个序列?
postgresql activerecord ruby-on-rails rails-migrations rails-activerecord