Rails 如何将所有活动存储附件复制到新对象?
Rails how to copy all active storage attachments to new object?
我有一个功能可以在 rails 应用程序中克隆记录。除了表单数据之外,我还想 copy/attach 将附加到源对象的任何活动存储文件上传到新对象。关于如何做到这一点的任何想法?这是我的操作:
def copy
@source = Compitem.find(params[:id])
@compitem = @source.dup
render 'new'
end
class Compitem < ApplicationRecord
belongs_to :user
has_many_attached :uploads, dependent: :destroy
end
我最终通过使用 https://github.com/moiristo/deep_cloneable gem 来完成这项工作。最后行动:
def copy
@source = Compitem.find(params[:id])
@compitem = @source.deep_clone(include: :uploads_blobs)
@compitem.save
render 'new'
end
只是在我的一个应用程序中这样做了 - 它是 has_one 而不是 has_many 但我认为这样的东西应该适合你,而不添加任何额外的依赖项,在 Rails 6+:
@compitem = @source.dup
@source.uploads.each do |original_file|
@compitem.uploads.attach(io: StringIO.new(original_file.download),
filename: original_file.filename,
content_type: original_file.content_type)
end
@compitem.save
我有一个功能可以在 rails 应用程序中克隆记录。除了表单数据之外,我还想 copy/attach 将附加到源对象的任何活动存储文件上传到新对象。关于如何做到这一点的任何想法?这是我的操作:
def copy
@source = Compitem.find(params[:id])
@compitem = @source.dup
render 'new'
end
class Compitem < ApplicationRecord
belongs_to :user
has_many_attached :uploads, dependent: :destroy
end
我最终通过使用 https://github.com/moiristo/deep_cloneable gem 来完成这项工作。最后行动:
def copy
@source = Compitem.find(params[:id])
@compitem = @source.deep_clone(include: :uploads_blobs)
@compitem.save
render 'new'
end
只是在我的一个应用程序中这样做了 - 它是 has_one 而不是 has_many 但我认为这样的东西应该适合你,而不添加任何额外的依赖项,在 Rails 6+:
@compitem = @source.dup
@source.uploads.each do |original_file|
@compitem.uploads.attach(io: StringIO.new(original_file.download),
filename: original_file.filename,
content_type: original_file.content_type)
end
@compitem.save