ruby-on-rails - 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
- 编辑.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>
非常感谢我能得到的任何帮助。
解决方案
@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_id
在product_params
. 它可能看起来像:
<%= f.input :seller_id, :input_html => { :value => @seller.id } %>
推荐阅读
- spring-boot - 如何解决“在类路径资源中定义的 BeanDefinition 中定义的 bean 'dataSource'”?
- sql - 在 Postgresql 中一级取消嵌套多维数组
- android - Android 通知无法与 AlarmManager 一起正常工作
- laravel - 如何使用 phpmailer 或 swiftmailer 将 laravel 与 powermta 连接?
- sails.js - 是否有像 cls-rtracer 这样的包可以在sails.js 中使用请求ID 进行记录?
- node.js - 将 2 个 MongoDB 集合合并为一个 api URL(不合并集合,将它们分开)
- javascript - 当 div 触摸浏览器顶部时添加类
- php - 身份验证时未从中间件获取用户角色
- sql - 使用标准 SQL 在两个数字后添加冒号
- python - scipy.optimize.minimum with 'trust-constr' 给出不同初始值的不同最优值