Ruby On Rails [Carrierwave]: 无法删除图像

Ruby On Rails [Carrierwave]: Cannot delete image

我是 rails 的新手,正在尝试使用 'carrierwave-ftp' gem 将图片上传到 ftp。对于图片上传,我有两个控制器。第一个是 'events_controller' 而第二个是 'events_pictures_controller'.

图片正在上传到 ftp。但问题是,当我删除单张照片时,它正在破坏整个事件。请帮忙!

这是我的事件模型:

class Event < ActiveRecord::Base
  has_many :event_pictures, dependent: :destroy
  accepts_nested_attributes_for :event_pictures, allow_destroy: true
  validates_presence_of :name, :date
end

这是我的 EventPictures 模型:

class EventPicture < ActiveRecord::Base
  mount_uploader :picture_title, EventPicturesUploader
  validates_presence_of :picture_title
  belongs_to :event, dependent: :destroy
end

事件控制器:

def index
    @events = Event.all.order('date DESC')
end  

def show
    @event_pictures = @event.event_pictures.all
end

def new
    @event = Event.new
    @event_picture = @event.event_pictures.build
end

def edit
end

def create
    @event = Event.new(event_params)
      respond_to do |format|
        if @event.save
          params[:event_pictures]['picture_title'].each do |a|
            @event_picture = @event.event_pictures.create!(:picture_title => a, :event_id => @event.id)
          end
      format.html { redirect_to @event, notice: 'Event was successfully created.' }
        else
      format.html { render :new }
    end
  end
end

def destroy
    @event = Event.find params[:id]
    @event.destroy
    redirect_to events_url
end

private
  def set_event
      @event = Event.find(params[:id])
  end

  def event_params
      params.require(:event).permit(:name, :date, event_pictures_attributes: [:id, :event_id, :picture_title])
  end

这是 EventPictures Controller 中的 Destroy 方法

def destroy
    @event_picture = EventPicture.find params[:id]
    @event_picture.destroy
    redirect_to "events_url"
end

与此同时,在 events.show.html.erb 中,我有这个:

<% @event_pictures.each do |p| %>    
      <%= link_to image_tag(p.picture_title_url, :class => 'event-img'), image_path(p.picture_title_url) %>
      <%= link_to 'Delete', p, method: :delete, data: { confirm: "Are you sure?" } %>
<% end %>

我认为你的错误在于这一行

belongs_to :event, dependent: :destroy

这是告诉EventPicture模型在删除时删除它的父模型Event。

替换为

belongs_to :event

在你的EventPicture模型中你有dependent: :destroy关联,这意味着当图片也会删除相应的事件。所以只需编辑关联并使其成为:

belongs_to :event

并且您依赖 Event 模型进行销毁,因此当事件将被删除时,相应的图片也会被删除,这是正确的。

希望对您有所帮助。