我有以下模型:
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
为insights_id
列生成nextval('public.models_insights_id_seq')
,而不是使用 ActiveRecord 获取序列的下一个值。
最佳答案
今天遇到同样的问题。只是使用另一种方式进行记录导入。不是导入 AR 对象集合,而是构建一个不带序列参数的属性哈希集合,然后通过 Model.import
导入它们。这种方式对我有用。
例子。鉴于我有默认序列值的位置列:
位置 |整数 |不为空默认 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)
关于ruby-on-rails - 如何使 activerecord-import 使用序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53832590/