0

posts我需要使用已翻译的属性保存大量body,因此我尝试将insert_all/upsert_allMobility结合使用。单独保存帖子就可以了:

Post.create({
  body_en: "Hello world",
  body_ja: "ハロー・ワールド",
  ...
})

但是,尝试使用insert_all会导致错误,因为body它没有存储在帖子表中,而是存储在通过多态关联相关的mobility_text_translations 表中(我使用的是默认键/值后端):

posts = []

# In a loop, add many posts to the posts array
post = {
  body_en: "Hello world",
  body_ja: "ハロー・ワールド".
  ...
}

posts << post

# Add posts to DB at some interval
Post.insert_all(posts)
# => unknown attribute 'body_en' for Post. (ActiveModel::UnknownAttributeError)

我认为这有点类似于ActionText,而不是ActionText::RichText.insert_all(post_bodies)我想知道我们是否可以做类似Mobility::TextTranslations.insert_all(post_bodies). 但是,我没有在 GitHub 页面和问题中看到此功能的讨论。

4

1 回答 1

0

此行为是因为 Mobility 在您调用 create 时处理单个条目,如下所示 -

  1. before_save 回调触发;
  2. 如果模型没有属性,例如body_fr,则将其从条目列表中删除,而是在 Mobility 表中为body属性和fr区域创建一个条目,并带有指向表中主条目的链接posts

在 ActiveRecord 中执行批量操作不会触发此回调。因此,如果您想提高插入或更新许多记录的速度,您可以在事务中包装关于数据的迭代。

data = [{body_en: 'aaa', body_fr: 'aaa'}, {body_en: 'bbb', body_fr: 'bbb'}]
::ActiveRecord::Base.transaction do
  data.each do |post|
    Post.create(post)
  end
end
于 2022-01-28T13:20:19.507 回答