2011-01-15 9 views
5

Я не могу найти пример, который будет заполнен во всех компонентах. Я с трудом удаляемого вложения изображенияrails 3, paperclip (& formtastic) - удаление вложений изображений

  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»?

ответ

10

Из API Docs для ActiveRecord::NestedAttributes::ClassMethods

:. Allow_destroy

Если это правда, разрушающей любые члены из атрибутов хэш с ключом _destroy и значение, которое имеет значение истина (например, 1, '1', true или 'true'). По умолчанию эта опция отключена.

Итак:

accepts_nested_attributes_for :product_images, allow_destroy: true 
+0

ARGH! Да ты прав! Благодаря! – phil

+0

ради полноты строки должна быть: accepts_nested_attributes_for: product_images,: allow_destroy => true – phil

+0

Завершено, то: P – noodl

Смежные вопросы