Rails 3,Paperclip(和Formtastic)-删除图像附件

5

我似乎找不到一个完整的例子,其中所有组件都齐全。我在删除图像附件方面遇到了困难。

  1. Classes

      class Product
        has_many :product_images, :dependent => :destroy
        accepts_nested_attributes_for :product_images
      end
    
      class ProductImage
        belongs_to :product
        has_attached_file :image #(etc)
      end
    
  2. View

      <%= semantic_form_for [:admin, @product], :html => {:multipart => true} do |f| %>
        <%= f.inputs "Images" do %>
          <%= f.semantic_fields_for :product_images do |product_image| %>
            <% unless product_image.object.new_record? %>
              <%= product_image.input :_destroy, :as => :boolean, 
                 :label => image_tag(product_image.object.image.url(:thumb)) %>
            <% else %>
              <%= product_image.input :image, :as => :file, :name => "Add Image" %>
            <% end %>
          <% end %>
        <% end %>
      <% end %>
    
  3. Controller

      class Admin::ProductsController < AdminsController
       def edit
         @product = Product.find_by_permalink(params[:id])
         3.times {@product.product_images.build} # added this to create add slots
       end
    
       def update
          @product = Product.find_by_permalink(params[:id])
    
          if @product.update_attributes(params[:product])
            flash[:notice] = "Successfully updated product."
            redirect_to [:admin, @product]
          else
            flash[:error] = @product.errors.full_messages
            render :action => 'edit'
          end
        end
      end
    

看起来不错,但是当我勾选复选框时实际上没有任何反应。

在请求中我看到:

      "product"=>{"manufacturer_id"=>"2", "size"=>"", "cost"=>"5995.0", 
         "product_images_attributes"=>{"0"=>{"id"=>"2", "_destroy"=>"1"}}

但是没有任何更新,产品图片也没有保存。
我是否对“accepts_nested_attributes_for”如何工作的基本原理有所遗漏?
1个回答

11

根据ActiveRecord::NestedAttributes::ClassMethods的API文档:

:allow_destroy

如果为true,则销毁属性哈希中具有_destroy键且值计算结果为true(例如1,'1',true或'true')的任何成员。默认情况下禁用此选项。

因此:

accepts_nested_attributes_for :product_images, allow_destroy: true

为了完整性,该行应为:accepts_nested_attributes_for:product_images,:allow_destroy => true - phil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接