Search code examples
ruby-on-railsrails-migrationsactiontext

Copy an ActionText field to a plain text field Rails


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


Solution

  • 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