3

我有以下模型:

                                                  Table "public.models"
        Column        |            Type             | Collation | Nullable |                   Default                   
----------------------+-----------------------------+-----------+----------+---------------------------------------------
 id                   | bigint                      |           | not null | nextval('models_id_seq'::regclass)
 research_provider_id | bigint                      |           | not null | 
 covered_company_id   | bigint                      |           | not null | 
 publication_date     | timestamp without time zone |           | not null | 
 created_at           | timestamp without time zone |           | not null | 
 updated_at           | timestamp without time zone |           | not null | 
 insights_id          | bigint                      |           | not null | nextval('models_insights_id_seq'::regclass)
Indexes:
    "models_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "fk_rails_22d32db7ac" FOREIGN KEY (covered_company_id) REFERENCES companies(id)
    "fk_rails_3a764bb9c1" FOREIGN KEY (research_provider_id) REFERENCES companies(id)
Referenced by:
    TABLE "model_product_groups" CONSTRAINT "fk_rails_1866a14ba0" FOREIGN KEY (model_id) REFERENCES models(id)
    TABLE "model_analysts" CONSTRAINT "fk_rails_c7730c705b" FOREIGN KEY (model_id) REFERENCES models(id)

我正在使用 ActiveRecord 创建对象,其中:

   Model.new(
        # insights_id: 
        research_provider_id: company.id,
        covered_company_id: covered_company_id,
        publication_date:  Time.current - rand(1..20).day,
    ......
   )

我应该传递什么值insights_id才能使用models_insights_id_seq序列?尝试DEFAULT并没有传递任何东西,并且都无法使用序列,即,使 activerecord-import 生成nextval('public.models_insights_id_seq')

注意:这个问题是关于指示为列activerecord-import生成,而不是关于使用 ActiveRecord 获取序列下一个值。nextval('public.models_insights_id_seq')insights_id

4

1 回答 1

1

今天面临同样的问题。只是使用另一种方式进行记录导入。与其导入 AR 对象集合,不如构建一个不带序列参数的属性哈希集合,然后通过Model.import. 这种方式对我有用。

例子。鉴于我有默认序列值的位置列: position | integer | not null default nextval('file_exports.task_file_item_position_seq'::regclass)

在这段代码中,下一个序列值将由 Postgres 在每条FileExports::TaskFileItem记录中自动设置。

... 
params = file_records.map do |file_record|
  build_file_item_params(file_record) 
end 

def build_file_item_params(file_record) 
  { 
    name: "some_name", 
    link: file_record.file.url 
  } 
end 

FileExports::TaskFileItem.import!(params, validate: true) 
于 2020-05-21T12:50:36.203 回答