paperclip inputs and previews for uploaded images in edit action

那年仲夏 提交于 2019-12-05 17:47:02

Reject your unused file_fields:

# model
has_attached_file :attachment,
                     :styles => {
                       :medium => "600x600>",
                       :small => "200x200>",
                       :thumb => "100x100>" },
                     :default_url => "no_image_fr_:style.png",
                     :reject_if => lambda { |t| t['attachment'].nil? }

Update your edit action, so that it shows only remaining number of file fields

# controller
def edit
  @post = Post.find(params[:id])  
  @assets = @post.assets
  (3 - @assets.count).times { @assets.build }
end

Show already uploaded images and required file_fields.

<%= f.fields_for :assets do |builder| %>
  <%= builder.file_field :attachment %>
<% end %>

<p>Images</p>
<% @assets.each do |a| %>
  <%= link_to image_tag(a.attachment.url(:thumb)), a.attachment.url(:original) %>
  Delete: <%= check_box_tag :_destroy %>
<% end %>

Test it after cleaning up your assets table.

You might try only building new assets for the number of images that have not been created. Your edit action would look like this:

def edit
   @post = Post.find(params[:id])
   (3 - @post.assets.count).times do
     @post.assets.build
   end
end

also you'll want to keep in mind that if you're using accepts_nested_attributes_for in your Post model you might need to add the update_only: true

hope that helps! :)

I actually finally figured out a nice way to do this

to display only the remaining field fields I had to check if it was still a new record... even though assets.count was correct, the number of fields displayed was incorrect. This verification helped.

 <% if builder.object.new_record? %>

to display only the "filled" assets, I had to check if it's not a new record!

<% @post.assets.each do |ast| %>

  <% if !ast.new_record? %> 

   <%=link_to image_tag(ast.attachment.url(:thumb)), ast.attachment.url(:medium), :popup=>['original_image', 'height=700,width=900'] %>  <%= check_box_tag :_destroy %>   delete  </br></br>
   <%end%>

<% end %>

Now in the edit action it only shows the remaining fields... and when an asset is already filled, it shows a little preview with a deletion checkbox!

Still curious why the file fields were always showing 3 even though post.assets.count was correct.

I'm awarding the bounty to Raj who made considerable effort in trying to find a solution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!