gpt4 book ai didi

ruby-on-rails - 如何将 has_one_attached 转换为 has_many_attached 到带有 has_one 附件的现有表?

转载 作者:行者123 更新时间:2023-12-05 01:09:42 25 4
gpt4 key购买 nike

我有一个 Message 模型,它有

  class Message < ApplicationRecord
has_one_attached :attachment

但现在我需要将其转换为:

  class Message < ApplicationRecord
has_many_attached :attachments

为邮件启用多个附件所以我在模型 Message

中将 has_one_attached 改为 has_many_attached

但是当我运行 message.attachments.attached? 时,它会将 false 返回到现有附件。它适用于新附加的文件。

我应该添加手动添加/转换附件的迁移或一次性 rake 任务吗?

这样做的正确方法是什么?

最佳答案

message.attachments.attached? 返回 false 的原因是因为您将属性名称从 attachment 更改为 attachments。 ActiveStorage 将该属性名称保存在数据库中,因此如果该名称在代码中更改,它将无法再找到旧附件。

因此,要么不更改属性名称(最简单的解决方案),要么创建 data migration像这样

    ActiveStorage::Attachment.where(name: "attachment")
.where(record_type: "Message")
.update(name: "attachments")

关于ruby-on-rails - 如何将 has_one_attached 转换为 has_many_attached 到带有 has_one 附件的现有表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64858756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com