rails 3, paperclip (& formtastic) - 删除图片附件 [英] rails 3, paperclip (& formtastic) - deleting image attachments

查看:48
本文介绍了rails 3, paperclip (& formtastic) - 删除图片附件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法找到所有组件都完整的示例.我很难删除图片附件

I can't seem to find an example that is complete in all the components. I am having a hard time deleting image attachments

  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

  • 查看

  • 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 %>
    

  • 控制器

  • 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
    

  • 看起来不错,但是,当我选中复选框时,实际上没有任何反应.在请求中我看到:

    Looks good, but, literally nothing happens when I check the checkbox. In the request I see:

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

    但没有更新,产品图片也没有保存.

    But nothing gets updated and the product image is not saved.

    我是否遗漏了有关accepts_nested_attributes_for"工作原理的一些基本知识?

    Am I missing something fundamental about how 'accepts_nested_attributes_for' works?

    推荐答案

    来自 ActiveRecord::NestedAttributes::ClassMethods

    :allow_destroy

    :allow_destroy

    如果为 true,则使用 _destroy 键和计算结果为 true 的值(例如 1、‘1’、true 或 ‘true’)销毁属性哈希中的任何成员.此选项默认关闭.

    If true, destroys any members from the attributes hash with a _destroy key and a value that evaluates to true (eg. 1, ‘1’, true, or ‘true’). This option is off by default.

    所以:

    accepts_nested_attributes_for :product_images, allow_destroy: true
    

    这篇关于rails 3, paperclip (&amp; formtastic) - 删除图片附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆