在Ruby on Rails 5.2中的ActiveRecord迁移中,如何定义在创建表时使用的顺序? [英] How to define the sequence to use when creating a table in ActiveRecord migration in Ruby on Rails 5.2?

查看:85
本文介绍了在Ruby on Rails 5.2中的ActiveRecord迁移中,如何定义在创建表时使用的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为表的ID字段分配一个特定的Postgres序列.在模型中,我尝试定义以下对Posgres没有影响的设置:

I need to assign a specific Postgres sequence to the ID field of my table. In the model, I tried to define the following setup which has no effect on Posgres:

MyObject类< ActiveRecord :: Base

class MyObject < ActiveRecord::Base

self.sequence_name ="global_seq"

self.sequence_name = "global_seq"

通常,ActiveRecord迁移中的表定义始于

Usually, a table definition in ActiveRecord migrations start with

create_table "objects", id: :serial, force: :cascade do |t|

生成Postgres列默认值的定义为

which generates a Postgres definition of column default value as

default nextval('objects_id_seq'::regclass)

如何在迁移中指定nextval()函数应依赖另一个序列?

How can I specify in the migration that the nextval() function should rely on another sequence ?

推荐答案

您可以在迁移中更改默认设置:

You can change the default in a migration:

change_column :my_objects, :id, :integer, default: -> { "nextval('global_seq')" }

您可能希望使用:bigint而不是:integer,具体取决于序列和表的设置方式.您必须对:default选项使用lambda才能将原始的nextval('global_seq')表达式获取到数据库中.

You might want to use :bigint instead of :integer depending on how your sequence and tables are set up. You have to use a lambda for the :default option to get the raw nextval('global_seq') expression into the database.

您可能还希望删除旧序列,因此必须使用connection.execute('drop sequence ...')来代替AFAIK.

You might want to drop the old sequence as well, AFAIK you'd have to use connection.execute('drop sequence ...') for that.

如果您跳过create_table中的默认:id步骤,则可以在手动创建:id列时完成所有操作:

If you're skipping the default :id step in your create_table then you can do it all when you manually create the :id column:

create_table :my_objects, id: false do |t|
  t.bigint :id, null: false, default: -> { "nextval('global_seq')" }
  t.primary_key :id
  ...
end

同样,t.bigintt.integer之间的选择取决于您希望PK的大小.

Again, the choice between t.bigint and t.integer depends on how big you want your PK to be.

这篇关于在Ruby on Rails 5.2中的ActiveRecord迁移中,如何定义在创建表时使用的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆