开发者

Deleting images with paperclip

开发者 https://www.devze.com 2023-03-09 14:00 出处:网络
I\'m trying to delete each single image uploaded for a model (work has many images) but now my code works like this: I have three images uploaded in a work, I want to delete just one but when I check

I'm trying to delete each single image uploaded for a model (work has many images) but now my code works like this: I have three images uploaded in a work, I want to delete just one but when I check the image's checkbox and submit the update action it will delete all the three images.

Here is my work model's code:

  before_save :destroy_image?

  belongs_to :category
  has_many :images, :as => :assetable, :class_name => "Work::Image", :dependent =>    :dest开发者_StackOverflowroy

  accepts_nested_attributes_for :images, :reject_if => proc { |attributes| attributes['attachment'].blank? }

  def image_delete
    @image_delete ||= "0"
  end

 def image_delete=(value)
   @image_delete = value
 end

private
   def destroy_image?
    self.images.clear if @image_delete == "1"
   end


end


class Work::Image < Asset
   has_attached_file :attachment, :styles => {:small => "200x150>", :large =>    "400x300>"},
:url  => "/uploads/works/:id/:style/:basename.:extension",
:path => ":rails_root/public/uploads/works/:id/:style/:basename.:extension"

end

I think the problem is that delete all images

self.images.clear if @image_delete == "1"

but I don't understand how to fix it. I hope in your help.


You should use the :allow_destroy options of accepts_nested_attributes_for instead.

And in your form something like this:

<% @work.images.each do |image| %>
  <%= f.fields_for :images, image do |image_fields| %>
    <%= image_tag image.url(:small) %>
    <%= image_fields.check_box :_destroy %>
  <% end %>
<% end %>
0

精彩评论

暂无评论...
验证码 换一张
取 消