4

I am using refile and have two models:

class UserApplication < ActiveRecord::Base
  attachment :avatar
end

class User < ActiveRecord::Base
  attachment :avatar

  def from_application(application)
    # ...
    self.avatar = application.avatar
    # ...
  end
end

When I try to set up a User from UserApplication, the avatar attachment that has been associated with UserApplication is not saved with a User.

How can I duplicate or attach the UserApplication#avatar to the User instance?

Michał
  • 374
  • 1
  • 3
  • 16

1 Answers1

3

One way I found to do this is by calling the attachment download method and then setting a new id to the attachment. This will copy the file content and save the avatar to a new Refile::File when you save the model.

class User < ActiveRecord::Base
  attachment :avatar

  def from_application(application)
    self.avatar = application.avatar.download
    self.avatar_id = SecureRandom.alphanumeric(60).downcase
    save
  end
end

I'm using Refile 0.7.0 with refile-s3.

Rafael Fontoura
  • 326
  • 4
  • 12