首页 > 解决方案 > rails simple_forms 和 active_storage 图像在编辑产品时导致控制器错误

问题描述

我正在使用 Rails 构建一个小型市场应用程序,目前正试图让我的产品编辑和创建页面工作。我添加了图片上传功能,并使用简单的表单来添加产品的详细信息,但每当我尝试继续编辑时,我都会收到以下错误:

The action 'update' could not be found for ProductsController

同时,如果我尝试创建一个新产品,我会得到一个不同的错误:

{"seller":["must exist"]}

请在下面查看我的代码:

-products_controller.rb

  def create
    @product = Product.create 
    @product_id = @product.id 
      if @product.save
        render :show, status: :created
      else
        render json: @product.errors, status: :unprocessable_entity
      end

    end
  end


  # PATCH/PUT /products/1 or /products/1.json
  def update 
    @product = Product.update (product_params)
      if @product.save
        render products:id, status: :created
      else
        render json: @product.errors, status: :unprocessable_entity
      end
    end

 def product_params
      params.require(:product).permit(:title, :description, :price, :buyer_id, :seller_id, :category, :image_url)
    end
<%= simple_form_for edit_product_path, url: {action: "update"} do |f| %>
    <h1 class="heading">Edit Product</h1>
    <%= render 'form', product: @product %>
<% end %>

-form.html.erb

<div class="form-inputs">
    <%= f.input :title %>
    <%= f.input :description %>
    <%= f.input :price %>
    <%= f.input :category, collection: ["footwear", "accessories", "menswear", "womenswear"] %>
    <div class="form-group">
      <% if product.picture.attached? %>
        <%= image_tag product.picture, style: "width: 200px; display: block" %>
      <% end %>
      <%= f.file_field :picture %>
    </div>
  </div>

非常感谢我能得到的任何帮助。

标签: ruby-on-railsrubyrails-activestoragesimple-form-for

解决方案


    @product = Product.create 
    @product_id = @product.id 
      if @product.save
        render :show, status: :created
      else
        render json: @product.errors, status: :unprocessable_entity
      end

    end <--- extra end
  end

看起来您在创建操作的中间有一个额外的悬挂端。这可能会解释它发生了什么。

如果这不能解决问题,请确保您在routes.rb.

如果您不断收到seller must exist错误消息,Rails 5/6 会自动假定belongs_to关联将存在一个模型,以便在保存记录时关联到该模型。optional: true您可以通过添加到您的关系定义中来关闭它,如下所示:

class Product
   belongs_to :seller, optional: true
end

只要seller_idproduct_params. 它可能看起来像:

<%= f.input :seller_id, :input_html => { :value => @seller.id } %>


推荐阅读