gpt4 book ai didi

ruby-on-rails - rails 3,回形针(和 formtastic) - 删除图像附件

转载 作者:行者123 更新时间:2023-12-04 17:12:59 24 4
gpt4 key购买 nike

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

  • 类(class)
      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 %>
  • 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

  • 看起来不错,但是,当我选中复选框时,实际上没有任何 react 。
    在请求中我看到:
          "product"=>{"manufacturer_id"=>"2", "size"=>"", "cost"=>"5995.0", 
    "product_images_attributes"=>{"0"=>{"id"=>"2", "_destroy"=>"1"}}

    但没有任何更新,产品图片也不会保存。

    我是否缺少有关“accepts_nested_attributes_for”如何工作的基本知识?

    最佳答案

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

    :allow_destroy

    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

    关于ruby-on-rails - rails 3,回形针(和 formtastic) - 删除图像附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4699765/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com