Reputation: 658
How do I duplicate an ActiveRecord object with a dragonfly image?
I have the following.
model:
class Event < ActiveRecord::Base
image_accessor :thumbnail
attr_accessible :thumbnail, :remove_thumbnail, :retained_thumbnail
validates :thumbnail, presence: true
end
controller:
def clone
@event = Event.find(1).dup
render :new
end
view:
<%= form_for @event do |f| %>
<%= f.label :thumbnail %>
<%= image_tag(@event.thumbnail.thumb('100x75').url) %>
<label><%= f.check_box :remove_thumbnail %> Remove?</label>
<%= f.file_field :thumbnail %>
<%= f.hidden_field :retained_thumbnail %>
<% end %>
When I render the form, the image displays, but on submit, the image gets cleared out.
One thing, I'd like to make sure they are actually different images, so if I edit the original record, it will not affect the duplicate.
Upvotes: 2
Views: 710
Reputation: 4870
Here's how I got it to work, overriding the object's dup
behavior:
def dup
target = Event.new(self.attributes.reject{|k,v| ["id", "attachment_uid"].include?(k) })
target.attachment = self.attachment
target
end
Then, when you call save
on the target the image will be copied to the new location.
Note that on the first line I first tried target = super
, to utilize the object's default dup
behavior, but that caused the files of the original object to be deleted. The above solution finally did the trick for me.
Upvotes: 2