5

我似乎找不到在所有组件中都完整的示例。我很难删除图片附件

  1. 课程

      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. 看法

      <%= 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. 控制器

      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”如何工作的基本知识?

4

1 回答 1

11

来自ActiveRecord::NestedAttributes::ClassMethods的 API 文档

:allow_destroy

如果为 true,则使用 _destroy 键和评估为 true 的值(例如 1、'1'、true 或 'true')销毁属性散列中的任何成员。此选项默认关闭。

所以:

accepts_nested_attributes_for :product_images, allow_destroy: true
于 2011-01-15T13:23:13.647 回答