我似乎无法在所有组件中找到完整的示例。我很难删除图片附件
类
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
查看
<%= 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 %>
控制器
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'如何运作的基本信息?
答案 0 :(得分:10)
来自ActiveRecord::NestedAttributes::ClassMethods
的API文档:allow_destroy
如果为true,则使用_destroy键和值为true的值(例如,1,'1,true或'true')销毁属性哈希中的所有成员。默认情况下,此选项处于关闭状态。
所以:
accepts_nested_attributes_for :product_images, allow_destroy: true