【问题标题】:Copy an ActionText field to a plain text field Rails将 ActionText 字段复制到纯文本字段 Rails
【发布时间】:2021-10-28 20:37:48
【问题描述】:

我需要在 Rails ActionText 字段中搜索文本。找不到任何解决方案,所以我创建了一个纯文本字段,并在提交 ActionText 表单时运行 before_ save self.content_plain_text = content.body.to_plain_text。这很好用,我可以在content_plain_text 中搜索。

但现在我需要为所有已经存在的数据更新content_plain_text。找到这个有迁移的How do I move a column (with contents) to another table in a Rails migration?。我以为我可以模仿它,但这不起作用。

class CopyContentToContentPlainText < ActiveRecord::Migration[6.0]
  def up
    Doc.find_each do |d|
      content_plain_text = action_text_rich_texts.record_id[d].content.body.to_plain_text
      Content.create!(doc_id: d.id, content_plain_text: content_plain_text)
    end
  end
end

我在获取 ActionText 字段时迷失了方向。 record_id对应doc_id

【问题讨论】:

    标签: ruby-on-rails rails-migrations actiontext


    【解决方案1】:

    正如你已经定义的before_save

    before_save { self.content_plain_text = content.body.to_plain_text }
    

    那么每当你调用a_doc.save时,before_save就会被触发,因此content_plain_text会被分配给content.body.to_plain_text

    这样您就可以为所有Doc 记录更新content_plain_text,只需简单调用save

    class CopyContentToContentPlainText < ActiveRecord::Migration[6.0]
      def up
        Doc.find_each(&:save)
      end
    end
    

    【讨论】:

    • 谢谢。更近了。错误:undefined method to_plain_text' for nil:NilClass. I removed the .to_plain_text` 和 rails db:migrate DRY_RUN=true 去了。我从来没有做过试运行,但输出是有道理的。迁移时无法访问该方法?
    • @Greg 那个错误是因为有一些Doc记录没有丰富的内容content.body,所以你可以在before_save上检查nil。
    • 谢谢。我想就是这样。花了我一分钟。我的移民历史很混乱。试运行现在正在进行,输出看起来正确。我在最大的模型中只有几千件物品。这在大型数据库上可能是一个问题,但这对我来说很好。再次感谢。我已经备份了我的数据库并将真正运行它。问题还没有出现,因为我只保存了几个条目,而且它们都不是零。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-02
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    相关资源
    最近更新 更多