Michał
Michał

Reputation: 373

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?

Upvotes: 4

Views: 181

Answers (1)

Rafael Fontoura
Rafael Fontoura

Reputation: 324

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.

Upvotes: 3

Related Questions