我有一个Rails 5网络应用程序,它正在尝试使用 woo commerce api 将订单发布回wordpress网站。
我正在使用的宝石包装纸是:
gem "woocommerce_api"
如果我对一个订单项进行硬编码,则可以完美地创建订单。但是,我不知道如何添加多个订单项。请参见下面的第一个“有效示例”,然后请参见下文尝试遍历订单项的内容。
我得到的错误响应是:
{"code"=>"woocommerce_rest_required_product_reference", "message"=>"Product ID or SKU is required.", "data"=>{"status"=>400}}
很明显,我不应该在请求中添加.each循环...但是我不知道其他方式吗?
工作后请求
@cart_items = Cart.where(user_id: @user.id).all
data = {
status: "processing",
currency: "AUD",
set_paid: true,
billing: {
first_name: "#{@user.first_name}",
last_name: "#{@user.last_name}",
address_1: "#{@user.address}",
address_2: "",
city: "#{@user.suburb}",
state: "#{@user.state}",
postcode: "#{@user.postcode}",
country: "Australia",
email: "#{@user.email}",
phone: "#{@user.phone}"
},
shipping: {
first_name: "#{@user.first_name}",
last_name: "#{@user.last_name}",
address_1: "#{@user.address}",
address_2: "",
city: "#{@user.suburb}",
state: "#{@user.state}",
postcode: "#{@user.postcode}",
country: "Australia",
},
line_items: [
{
:product_id => 123,
:variation_id => 1,
:quantity => 2
:subtotal => "10.00",
:total => "20.00"
}
],
shipping_lines: [
{
method_id: "flat_rate",
method_title: "Flat Rate",
total: "0"
}
]
}
失败的多行项目请求
@cart_items = Cart.where(user_id: @user.id).all
data = {
status: "processing",
currency: "AUD",
set_paid: true,
billing: {
first_name: "#{@user.first_name}",
last_name: "#{@user.last_name}",
address_1: "#{@user.address}",
address_2: "",
city: "#{@user.suburb}",
state: "#{@user.state}",
postcode: "#{@user.postcode}",
country: "Australia",
email: "#{@user.email}",
phone: "#{@user.phone}"
},
shipping: {
first_name: "#{@user.first_name}",
last_name: "#{@user.last_name}",
address_1: "#{@user.address}",
address_2: "",
city: "#{@user.suburb}",
state: "#{@user.state}",
postcode: "#{@user.postcode}",
country: "Australia",
},
line_items: [
@cart_items.each do |ci|
{
:product_id => ci.product.woo_id.to_i,
:variation_id => 0,
:subtotal => ci.product.price.to_s,
:total => ((ci.product.price.to_d * ci.quantity.to_i).round(2)).to_s
}
end
],
shipping_lines: [
{
method_id: "flat_rate",
method_title: "Flat Rate",
total: "0"
}
]
}
答案 0 :(得分:1)
我相信问题与使用each
方法有关。
关于
each
方法要记住的最重要的事情是它不会更改返回值。它隐式返回原始数组。
请改为查看map
或collect
方法,该方法“创建一个包含该块返回的值的新数组”。
...
line_items: @cart_items.map do |ci|
{
:product_id => ci.product.woo_id.to_i,
:variation_id => 0,
:subtotal => ci.product.price.to_s,
:total => ((ci.product.price.to_d * ci.quantity.to_i).round(2)).to_s
}
end,
...
但是,正如您所说的那样,在数据有效载荷中使用方法并不便于阅读,因此我建议您将其重构为变量:
@line_items = ...map function here...
data: {
...
line_items: @line_items
...
或进入Cart
模型中的实例方法。