【问题标题】:Rails Action Text for existing text field现有文本字段的 Rails 操作文本
【发布时间】:2020-01-02 07:01:24
【问题描述】:

我正在将我的一个新闻应用程序升级到 Rails 6.0.0。在解决问题时,我在使用富文本时遇到了问题。我的应用程序指向富文本正文字段,而不是我现有的表格正文字段。

是否可以将现有的表格文本字段用于富文本,以便我可以在需要时编辑内容。与新帖子一样,我可以使用 action_text_rich_texts 表,但对于现有帖子,我想使用现有的表格正文字段。

【问题讨论】:

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


    【解决方案1】:

    ActionText 的助手 has_rich_text defines 为您提供 getter 和 setter 方法。

    您可以再次重新定义body 方法,为ActionText 提供使用read_attribute 存储在表中的值:

    class Post
      has_rich_text :body
    
      # Other stuff...
      
      def body
        rich_text_body || build_rich_text_body(body: read_attribute(:body))
      end
    

    【讨论】:

    • 优雅的解决方案!不过应该是read_attribute(:body)。该解决方案的优点是逐步转换带有旧文本的大型数据库,而不是在迁移期间对数据库进行繁重的处理(可能会循环数千个条目)。谢谢!
    • 谢谢!我已更新代码以修复错字
    【解决方案2】:

    假设您的模型中有一个 content 并且这就是您要迁移的内容,首先,添加到您的模型中:

    has_rich_text :content
    

    然后创建迁移

    rails g migration MigratePostContentToActionText
    

    结果:

    class MigratePostContentToActionText < ActiveRecord::Migration[6.0]
      include ActionView::Helpers::TextHelper
      def change
        rename_column :posts, :content, :content_old
        Post.all.each do |post|
          post.update_attribute(:content, simple_format(post.content_old))
        end
        remove_column :posts, :content_old
      end
    end
    

    请参阅此Rails Issue comment

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      • 2017-03-25
      相关资源
      最近更新 更多