我对ActiveStorage有个问题
在这种情况下,我有一个名为Setting::Profile的模型,Admin表的名称和附件:avatar用于上传过程成功,但是无法找到何时获取图片的方法,因为在表active_storage_attachments中,属性record_type中存储有名称Setting::Profile,假定为名称Admin。
如何添加一行来准备record_type属性?谢谢
这是我的演示:https://github.com/SunDi3yansyah-forks/AppActiveStorage

发布于 2018-07-12 08:30:42
我发现了这个问题(尝试在控制台中)。
如果您设置了profile = Account::Profile.last,然后调用profile.avatar.attached?,它将返回profile.avatar.attached?。这是因为ActiveStorage::Attachment中的列ActiveStorage::Attachment设置为User。
因此,您无法访问blob,因为profile.avatar.blob返回以下查询:
SELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" = ? AND "active_storage_attachments"."record_type" = ? AND "active_storage_attachments"."name" = ? LIMIT ? [["record_id", 1], ["record_type", "Account::Profile"], ["name", "avatar"], ["LIMIT", 1]]错误:Module::DelegationError: blob delegated to attachment, but attachment is nil
我发现的一个可能的解决办法是定义::Profile,如下所示:
class Account::Profile < ApplicationRecord
self.table_name = "users"
# has_one_attached :avatar # remove this
def avatar
ActiveStorage::Attachment.where(name: :avatar, record_type: 'User', record_id: self.id).last
end
end这可以显示图像,但问题是profile.avatar.class不是ActiveStorage::Attached::One (像User.last.avatar.class),而是ActiveStorage::Attachment。
因此,您不能在上面调用例如.attached?方法。您必须使用profile.avatar.present?来检查化身是否存在。
一个更好的解决方案是以这种方式定义实例方法avatar:
def avatar
ActiveStorage::Attached::One.new('avatar', User.find(id), dependent: :purge_later)
end它需要实例化ActiveStorage::Attached::One的一个对象,但是记录必须是User类(为了匹配record_type),这就是为什么User.find(id)。现在所有的方法都可用了:profile.avatar.methods。
https://stackoverflow.com/questions/51200105
复制相似问题