ruby-on-rails - 如何使 activerecord-import 使用序列
问题描述
我有以下模型:
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
解决方案
今天面临同样的问题。只是使用另一种方式进行记录导入。与其导入 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)
推荐阅读
- javascript - 使用 Ajax 在完整日历上显示数据而不显示记录
- c++ - 我如何获取引脚 4 的值以发送到从机并使用 I2C 显示?
- javascript - 是否可以使用 flatbuffers 将序列化数据流式传输到文件中?
- r - 我想模拟具有不同样本大小 n、不同 SD 值和不同 theta 值的一阶 MA(1) 的移动平均过程
- excel - 当两列重复时,如何在 Excel 中使用条件格式突出显示?
- javascript - 将 onPress 重定向传递给子组件 React Native
- telepot - from tensorflow.lite.python.interpreter import Interpreter 防止 Telepot
- python - 如何使用 Python 抓取特定字段,如下面的 HTML 代码所示?
- git - 如何使用搜索关键字和排序获取 git 标签
- python - 'if statement' 删除所有不符合条件的行,我不想要那个