0

I need to search text in a Rails ActionText field. Couldn't find any solutions, so I created a text plain field and when the ActionText form is submitted, a before_ save self.content_plain_text = content.body.to_plain_text is run. This works fine and I can search in content_plain_text.

But now I need to update the content_plain_text for all the already existing data. Found this How do I move a column (with contents) to another table in a Rails migration? which has a migration. And I thought I could mimic that, but this isn't working.

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

I'm lost in getting an ActionText field. record_id corresponds to the doc_id

Greg
  • 2,359
  • 5
  • 22
  • 35

1 Answers1

1

As you already define before_save

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

then whenever you call a_doc.save, the before_save will be triggered , hence, it's content_plain_text will be assigned to content.body.to_plain_text.

so you could update content_plain_text for all Doc records just simple call save

class CopyContentToContentPlainText < ActiveRecord::Migration[6.0]
  def up
    Doc.find_each(&:save)
  end
end
Lam Phan
  • 3,405
  • 2
  • 9
  • 20
  • Thank you. Much closer. Error: `undefined method `to_plain_text' for nil:NilClass`. I removed the `.to_plain_text` and `rails db:migrate DRY_RUN=true` went. I've never done a dry run, but the output makes sense. The method isn't accessible while migrating? – Greg Aug 30 '21 at 14:19
  • 1
    @Greg that error cause there're some Doc records which have not rich content `content.body`, so you could check nil on `before_save`. – Lam Phan Aug 30 '21 at 14:28
  • Thank you. I think that's it. Took me a minute. My migration history got confused. Dry run is going now and output looks right. I've only a few thousand items in the largest model. This might be a problem on a large db, but this is fine for my case. Thanks again. I've backed up my db and will run it for real. The problem hadn't shown up yet because I only had saved on a couple of entries and they all were not nil. – Greg Aug 30 '21 at 14:50