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