【问题标题】:rails simple_forms and active_storage images are resulting in controller errors when editing productsrails simple_forms 和 active_storage 图像在编辑产品时导致控制器错误
【发布时间】:2021-08-12 06:01:46
【问题描述】:

我正在使用 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
  • edit.html.erb
<%= 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-rails ruby rails-activestorage simple-form-for


    【解决方案1】:
        @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
    

    只要在product_params 中添加适当的过滤器,您就可以在页面加载时将seller_id 包含在您的SimpleForm 中并将其与之关联。它可能看起来像:

    &lt;%= f.input :seller_id, :input_html =&gt; { :value =&gt; @seller.id } %&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多