Carrierwave文件删除

Ryd*_*use 5 ruby ruby-on-rails carrierwave

我再次需要你的帮助.现在我需要了解如何删除Carrierwave上传的文件(在我的情况下 - 图像).

models/attachment.rb:

class Attachment < ActiveRecord::Base
  belongs_to :attachable, :polymorphic => true
  attr_accessible :file, :file
  mount_uploader :file, FileUploader
end
Run Code Online (Sandbox Code Playgroud)

models/post.rb:

class Post < ActiveRecord::Base
  attr_accessible :content, :title, :attachments_attributes, :_destroy
  has_many :attachments, :as => :attachable
  accepts_nested_attributes_for :attachments
end
Run Code Online (Sandbox Code Playgroud)

*views/posts/_form.html.erb:*

<%= nested_form_for @post, :html=>{:multipart => true } do |f| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% @post.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div id="field">
    <%= f.label :Nosaukums %>:<br /><br />
    <%= f.text_field :title %><br /><br />
  </div>
  <div id="field">
    <%= f.label :Raksts %>:<br /><br />
    <%= f.text_area :content %><br /><br />
  </div>

    <%= f.fields_for :attachments do |attachment| %>
    <% if attachment.object.new_record? %>
      <%= attachment.file_field :file %>

    <% else %>
      <%= image_tag(attachment.object.file.url) %>
      <%= f.check_box :_destroy %>
    <% end %>
  <% end %>


    <%= f.submit "Public?t", :id => "button-link" %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

当我试图删除以前上传的文件时,我有这个错误:

unknown attribute: _destroy
Run Code Online (Sandbox Code Playgroud)

也许有问题,因为我有多个文件上传不仅一个.

gbd*_*dev 11

这对我来说都不起作用,但在挖掘之后,我发现了这篇真正有用的帖子.基本上...

表单(其中f是表单对象):

<%= f.check_box :remove_image %>
Run Code Online (Sandbox Code Playgroud)

然后,如果您选中该框并提交表单,您将收到以下错误:

无法批量分配受保护的属性:remove_image

这是很容易通过简单地添加解决remove_image您的attr_accessible列表上的模型.最后,它看起来像:

class Background < ActiveRecord::Base
  attr_accessible :image, :remove_image
  belongs_to :user
  mount_uploader :image, BackgroundUploader
end
Run Code Online (Sandbox Code Playgroud)

在我的例子中,它是属于用户的背景图像.希望这可以帮助 :)


Jiř*_*šil 5

根据文档,该复选框应名为remove_file


Pol*_*her 3

您在错误的模型上调用该方法。您的文件装载位于附件中。

该错误告诉您出了什么问题。

undefined method 'remove_file' for #<Post:0x471a320
Run Code Online (Sandbox Code Playgroud)

错误的关键在于,当需要在 Attachment 模型上调用该方法时,却在 Post 模型上调用该方法。

也许尝试将复选框的输入范围限定为正确的模型。

<%= attachment.check_box :remove_file %>
Run Code Online (Sandbox Code Playgroud)