ruby-on-rails - 尝试创建新实例时,它会丢失这样做所需的相关参数
问题描述
导轨 5.1.6
我有一个应用程序,其中列出了产品,您可以将一定数量的产品添加到订单中。好吧,无论如何,这就是这个想法。所以,现在我有一个表格来获取数量,并获取产品 ID 和订单 ID,以便通过同样保存数量的 order_items 表将它们关联起来。看起来表单正在获取 order_id 并将其设置在 order_items 参数中。在这种情况下,数据库中确实存在 5. id 为 5 的订单。但是,当参数传递给 .new 时,它传递的是空白 id?我在这里想念什么?
ActiveRecord::RecordNotFound (找不到带有 'id'= 的订单): < wha?id 去哪儿了?
表格ERB
<% @products.each do |product| %>
<div class="col s4">
<h4><%= link_to product.name, product_path(product) %></h4>
<%= form_for @order_item do |f| %>
<%= f.hidden_field :order_id, value: @order.id %>
<%= f.hidden_field :product_id, value: product.id %>
<%= f.number_field :quantity, placeholder: "quantity" %>
<span class="waves-effect waves-light btn"><%= f.submit "Add to order" %></span>
<% end %>
</div>
类 OrderItemsController < ApplicationController
def create
@order = Order.find(params[:id])
@item = @order.order_items.new(item_params)
@order.save
if @order.save
flash[:notice] = "Your order has been added!"
redirect_to orders_path
else
render :new
end
end
def item_params
params.require(:order_item).permit(:quantity, :product_id, :order_id)
end
终端
Started POST "/order_items" for 127.0.0.1 at 2018-06-06 16:50:31 -0700
Processing by OrderItemsController#create as JS
Parameters: {"utf8"=>"✓", "order_item"=>{"order_id"=>"5",
"product_id"=>"2", "quantity"=>""}, "commit"=>"Add to order"}
Order Load (0.2ms) SELECT "orders".* FROM "orders" WHERE
"orders"."id" = $1 LIMIT $2 [["id", nil], ["LIMIT", 1]]
Completed 404 Not Found in 2ms (ActiveRecord: 0.2ms)
ActiveRecord::RecordNotFound (Couldn't find Order with 'id'=):
app/controllers/order_items_controller.rb:4:in `create'
解决方案
您的 :create 操作至少存在三处错误:
1)表单中的一个隐藏字段将 order_id 作为参数传递,您应该使用它来查找订单,如下所示:
@order = Order.find(params[:order_item][:order_id])
@order
2)您在 :create 操作中对实例调用 save 两次。
3)您实际上是在@order
实例变量上调用 save ,但在任何时候都没有保存@item
实例变量。@item
得救时@order
得救?
所以我会尝试以下方法:
def create
@order = Order.find(params[:order_item][:order_id])
# how come you don't save this? You instantiate it but don't appear to call save at any point.
@item = @order.order_items.new(item_params)
# remove the following line, which I've commented out:
# @order.save
# Consider whether you wish to save @order or @item, or both
if @order.save
flash[:notice] = "Your order has been added!"
redirect_to orders_path
else
render :new
end
end
希望对你有帮助,祝你好运
推荐阅读
- javascript - 使用 Node 的“加密”模块时是否需要使用密钥派生?
- javascript - JavaScript:按常见项目字段组合项目值列表
- api - 将 LogMeIn Refresh Token Curl 转换为 Coldfusion
- java - 在 Java 对象中发送 Multipart 和 JSON 数据 - Spring Boot Rest
- python - 网上银行网页抓取
- google-cloud-platform - 有没有办法通过存储在 Google Cloud Storage 中的文本文档进行 grep?
- html - 寻找更简洁的语法来使用 css 网格重复模式的列?
- python - Python:类方法中的 *args 行为
- javascript - jQuery.val() 仅在使用 datepicker 的第二个事件上返回值
- flutter - 如何显示html的一部分?