Rails删除照片库照片

时间:2013-12-17 05:56:33

标签: ruby-on-rails ruby-on-rails-4 paperclip

我正在使用:

  • Rails 4.0.1
  • paperclip 3.5.2

我设法创建了一个图库。使用模型PlaceGallery for Place模型。 PlaceGallery没有控制器,我不知道如何在库中删除这些图像。我使用了一个复选框等,但是当我更新地点时,它会复制丢失的图像。我应该将什么添加到我的场所控制器?

**place.rb**
class Place < ActiveRecord::Base

has_many :place_galleries, :dependent => :destroy
accepts_nested_attributes_for :place_galleries, :allow_destroy => true

end

**place_gallery.rb**
class PlaceGallery < ActiveRecord::Base

belongs_to :place
has_attached_file :image

end

**places_controller.rb**
class PlacesController < ApplicationController

def new
  @place = Place.new
  (3 - @place.place_galleries.length).times { @place.place_galleries.build }
end

def edit
  @place = Place.find_by_slug!(params[:id])
  (3 - @place.place_galleries.length).times { @place.place_galleries.build }
end

private
def set_place
  @place = Place.find_by_slug!(params[:id])
end

def place_params
  params.require(:place).permit(:title, :slug, :user_id, :place_type_id, :content, :address, :place_photo, place_galleries_attributes: :image)
end
end

**_form.html.erb** for Place
   <%= f.fields_for :place_galleries do |pg| %>
     <% if pg.object.new_record? %> 
       <%= pg.file_field :image %>
     <% end %>
   <% end %>

   <%= f.fields_for :place_galleries do |pg| %>
     <% unless pg.object.new_record? %> 
       <%= link_to(image_tag(pg.object.image.url(:small)), pg.object.image.url(:large))%>
       <%= pg.check_box :_destroy %>
     <% end %>
   <% end %>

Before updating. 2 checkboxes checked, so 2 photos should destroy, am i right? Some black magic happened here and 2 photos didn't delte, only duplicated 2 missing photos, but 1 uploaded photo uploaded right

1 个答案:

答案 0 :(得分:0)

通过添加params来解决我的问题:id和:_destroy到我的places_controller.rb

def place_params
  params.require(:place).permit(:title, :slug, :user_id, :place_type_id, :content, :address, :place_photo, place_galleries_attributes: [:image, :id, :_destroy])
end

这就是答案。

如果您不知道如何制作图片库,请尝试此操作 - http://www.emersonlackey.com/article/rails-paperclip-multiple-file-uploads并在运行rails 4时使用我的编辑。

感谢所有人。祝你好运!