Caching Image Uploads Across Page Loads with Rails -
caching image uploads across page loads rails problem
let’s imagine have form create blogpost title, body, , thumbnail image, , validate attributes present. this:
<% if @post.errors.any? %> <div> <h2><%= pluralize(@post.errors.count, "error") %> prohibited post being saved:</h2> <ul> <% @post.errors.full_messages.each |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> <div> <%= f.label :title %> <%= f.text_field :title %> </div> <div> <%= f.label :body %> <%= f.text_area :body %> </div> <div> <%= f.label :thumbnail %> <%= f.file_field :thumbnail %> </div> <div> <%= f.submit %> </div> <% end %>
consider following sequence of events: user fills in body field, selects thumbnail upload, , submits form. form renders again because title missing. user fills in missing title , re-submits form.
uh oh! validations fail because image missing!
the user has find image wanted upload again, irritating. avoid making user irritated.
the solution: image caching
carrierwave has great functionality caching uploaded file across form re-renders.
under file field, let’s add:
<%= f.hidden_field :thumbnail_cache %>
be sure add thumbnail_cache attr_accessible in rails 3, or permitted params in rails 4.
let’s add preview user can see current attached image:
<%= image_tag(@post.thumbnail_url) if @post.thumbnail? %>
now if user submits form missing title, thumbnail image selection sticks around. irritation avoided. great success.
it works fine...
but how add value <%= f.file_field :thumbnail %>
i have no file chosen
i have thumbnail_cache - file name
Comments
Post a Comment