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 %>