Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I duplicate a Refile attachment between Rails models?

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?

like image 601
Michał Avatar asked Sep 12 '25 00:09

Michał


1 Answers

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.

like image 105
Rafael Fontoura Avatar answered Sep 13 '25 16:09

Rafael Fontoura