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 に答える