首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使activerecord-import使用序列

如何使activerecord-import使用序列
EN

Stack Overflow用户
提问于 2018-12-18 20:02:19
回答 1查看 308关注 0票数 3

我有以下模型:

代码语言:javascript
复制
                                                  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创建对象,如下所示:

代码语言:javascript
复制
   Model.new(
        # insights_id: 
        research_provider_id: company.id,
        covered_company_id: covered_company_id,
        publication_date:  Time.current - rand(1..20).day,
    ......
   )

要使用models_insights_id_seq序列,我应该向insights_id传递什么值?尝试了DEFAULT,没有传递任何东西,两个都不能使用序列,例如,使用activerecord-import来生成nextval('public.models_insights_id_seq')

注意:这个问题是要指示activerecord-importinsights_id列生成nextval('public.models_insights_id_seq'),而不是关于使用ActiveRecord来获取序列的next值。

EN

回答 1

Stack Overflow用户

发布于 2020-05-21 20:50:36

今天也面临着同样的问题。只是使用了另一种记录导入方式。不导入AR对象的集合,而是构建一个不带序列参数的属性散列集合,然后通过Model.import导入它们。这种方式对我来说很有效。

举例说明。假设我有一个具有默认序列值的position列:position | integer | not null default nextval('file_exports.task_file_item_position_seq'::regclass)

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

代码语言:javascript
复制
... 
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) 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53832590

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档