如何使用 ActionText has_rich_text 播种数据?

How to seed data with ActionText has_rich_text?

在我的模型中,我有:

class Listing < ApplicationRecord
  ...
  has_rich_text :description
  ...
 end

在我的 seeds.rb:

@listing = Listing.new(
      title: 'CODE VEIN',
      price: 59.99 * 100,
      description:  "<p>#{Faker::Lorem.paragraphs(number: 30).join(' ')}</p>",
      seller_id: seller.id,
      release_date: Date.parse('Sep 26, 2019'),
      status: :active,
      esrb: 'MATURE'
    )

Listing.description 出现 nil,导致我的 NOT NULL 约束出错。

我用 pry 进行了调试,并尝试了 @listing.description.body= text@listing.description.body = ActionText::Content.new(text),两者仍然导致 listing#description 为 nil。

这是一个 API Only 项目,但我在前端 React 应用程序中使用了 Trix RTE。是否有特定的方法来播种 rich_text 列?

您的代码一定有其他问题。也许如果您共享您的迁移和完整的清单 class 文件,可能更容易发现正在发生的事情。

这里有几个步骤可以确保您做对了:

  1. 创建一个全新的 rails 应用程序(您可以稍后将其删除):
rails new testrichtext -d mysql --api
  1. 创建数据库
cd testrichclient
rake db:create
  1. 创建模型
rails g model listing description:text
  1. 更改您新创建的迁移文件以确保该列不为空:
class CreateListings < ActiveRecord::Migration[6.0]
  def change
    create_table :listings do |t|
      t.text :description, null: false

      t.timestamps
    end
  end
end

  1. 运行迁移
rake db:migrate
  1. 现在您应该可以登录到控制台,并创建一个新的列表,内容如下:
rails c

在控制台内:

l = Listing.new(description: "<p>Something nice</p>")
l.save!
Listing.first.description

如您所见,这足以 save/seed 新的富文本列表。因此,您可能发生的任何事情都应该是您在其他地方引起的,通过添加不同的验证或回调。不看整个文件很难说

ActionText 将实际内容存储在一个单独的 action_text_rich_texts table 中,它使用多态关联 link 回到它所附加的模型。

# This migration comes from action_text (originally 20180528164100)
class CreateActionTextTables < ActiveRecord::Migration[6.0]
  def change
    create_table :action_text_rich_texts do |t|
      t.string     :name, null: false
      t.text       :body, size: :long
      t.references :record, null: false, polymorphic: true, index: false

      t.timestamps

      t.index [ :record_type, :record_id, :name ], name: "index_action_text_rich_texts_uniqueness", unique: true
    end
  end
end

当用户与 Trix 交互时,ActionText 的 JavaScript 组件(这才是真正的重点)自动发送 AJAX 请求到 create/update [=11] 中的行=] table 甚至在您保存正在创建的记录之前。

当您随后提交表单时,您实际上是将 ID 提交到 action_text_rich_texts table 上的行,而不是内容。然后,当您保存模型时,它会使用模型中的 record_typerecord_id 更新 action_text_rich_texts 上的相应行。这是一个非常笨拙的解决方案,它是围绕永远不必向模型添加列的想法构建的。

我真的不明白在 API 中使用 ActionText 有什么意义,因为关键是要向经典 rails 应用程序添加一个快速而肮脏的 Trix 实现。你真的应该能够只用一个文本列来解决这个问题。尤其是这样,您无需加入即可访问内容。

我发现这对我有用:

15.times do
  Post.create!(title: Faker::Book.unique.title)
end

然后

Post.all.each do |post|
  ActionText::RichText.create!(record_type: 'Post', record_id: post.id, name: 'content', body: Faker::Lorem.sentence)
end

阅读:

Post.first.content.body.to_plain_text 

或:

Post.first.content.body.to_trix_html

...如 OP 所述。

来源: https://linuxtut.com/rails6-input-the-initial-data-of-actiontext-using-seed-9b4f2/