Ruby On Rails [Carrierwave]:不能删除镜像



我是rails的新手,试图用'carrier -ftp' gem实现图像上传到ftp。对于图像上传,我有两个控制器。第一个是'events_controller',第二个是' events_影视控制器'。

图片正在上传到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

Events Controller:

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。动词,我有这个

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

在您的EventPicture模型中,您在关联上有dependent: :destroy,这意味着当图片也将删除相应的事件时。编辑关联,输入:

belongs_to :event

你有依赖于Event模型的销毁,所以当一个事件将被删除时,相应的图片也将被删除,这是正确的。

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

belongs_to :event, dependent: :destroy

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

替换为

belongs_to :event

相关内容

  • 没有找到相关文章

最新更新