Reputation: 1853
I`m having troubles using carrierwave but it is not strictly related to it. I have Attachment model:
class Attachment < ActiveRecord::Base
attr_accessible :event_id, :file, :file_cache
belongs_to :event
mount_uploader :file, AttachmentUploader
end
which belongs to Event model
class Event < ActiveRecord::Base
ATTACHMENTS_LIMIT=3
attr_accessible ...
:attachments_attributes
...
has_many :attachments, :dependent => :destroy
accepts_nested_attributes_for :attachments
end
and a nested form like this:
<%= f.fields_for :attachments do |builder| %>
<fieldset class="attachment">
<%= builder.file_field :file %>
<%= builder.hidden_field :file_cache %>
<%= link_to_remove_fields t("actions.delete"), builder %>
</fieldset>
<% end %>
and it seems ok, unless once you get a validation error - then all file_fields are being reset with blank values. But there is a file_cache pointing to my carrierwave upload path(*uploads/tmp/20121003-1959-2388-3822/Getting_Started.pdf*).
How can i preserve files from being lost when validation error occurs??? Any tip would be greatly appreciated! I`ve smoked up those how-tos from official carrierwave wiki and related posts, but still no luck.
Upvotes: 2
Views: 686
Reputation: 164
Edit: After some investigation, I realize that my "image_path" field and before_validation method weren't necessary. All I had to do was this: https://github.com/jnicklas/carrierwave#making-uploads-work-across-form-redisplays. I'm not sure what the issue with the OP's code is... looks like it should work to me.
Just ran into this same problem. The fact that carrierwave keeps the file stored in a /tmp folder is very helpful. Here's what I did, in a nutshell:
Model:
class Image < AR:B
mount_uploader :image, ImageUploader
attr_writer :image_path
before_validation :set_image
def set_image
self.image = File.open(@image_path) if @image_path && !image.present?
true
end
end
View (using slim):
- if f.object.image.present?
= f.hidden_field :image_path, value: f.object.image.current_path
** Note: this exposes, in the raw html, the full path to the file on the production server. If that's a security concern for you, you could encrypt / decrypt the path, or set the value to be the raw image data or something.
Upvotes: 1