Home > front end >  Attaching a File to Multiple Objects
Attaching a File to Multiple Objects

Time:07-30

How can you beautifully attach the same file to multiple ActiveRecord objects?

object1.image.attach(params[:image])
blob = object1.image.blob
object2.image.attach(blob)
object3.image.attach(blob)
object4.image.attach(blob)

CodePudding user response:

Although not necessarily beautiful, it does get the job done with a minimal amount of code:

blob = ActiveStorage::Blob.create_and_upload!(io: file, filename: filename)
objects.each do |object|
  object.image.attach(blob)
end

But it would be great if we had a simple rails method something like this:

MyClass.image.attach(objects, params[:image])
  • Related