2013-12-17 59 views
0

我使用:的Rails刪除照片相冊

  • 的Rails 4.0.1
  • 回形針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

回答

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,用我的編輯,如果你運行的軌道4

感謝所有。祝你好運!