Ruby on rails Rails如何在my helper中构建自定义json请求
我正在使用一个API,并试图在助手中发布以下请求Ruby on rails Rails如何在my helper中构建自定义json请求,ruby-on-rails,ruby,json,post,httparty,Ruby On Rails,Ruby,Json,Post,Httparty,我正在使用一个API,并试图在助手中发布以下请求 module ShoppingCartHelper def update_order HTTParty.post("APIURL", :body => { @all_lines.each do |line| :ProductCode => line.ProductCode, :Quantity => line.Quantity,
module ShoppingCartHelper
def update_order
HTTParty.post("APIURL",
:body => {
@all_lines.each do |line|
:ProductCode => line.ProductCode,
:Quantity => line.Quantity,
:UnitPrice => line.UnitPrice,
:Pages =>
[
{
:PageNumber => line.PageNumber,
:Assets =>
[
{
:AssetNumber => line.AssetNumber,
:Name => line.Name,
:HiResImage => line.HiResImage,
:CropMode => line.CropMode
}
]
}
]
end
}.to_json,
:headers => { 'Content-Type' => 'application/json' })
end
end
当我这样做时,我会得到各种语法错误和意外字符@all_lines是数据库中一个订单的所有行,我试图为它找到的每一行构建json主体。。请帮忙
我没有使用像jbuilder这样的东西,因为我使用的所有字段都在一个表中。。它们没有链接到我可以包含它们的地方。除非有其他方法来创建自定义标签
更新:我需要此结构才能工作,但我收到语法错误:
HTTParty.post("APIURL",
:body =>
"Lines" =>
[
@all_lines.map do |line|
{
:ProductCode => line.ProductCode,
:Quantity => line.Quantity,
:UnitPrice => line.UnitPrice,
:Pages =>
[
{
:PageNumber => line.PageNumber,
:Assets =>
[
{
:AssetNumber => line.AssetNumber,
:Name => line.Name,
:HiResImage => line.HiResImage,
:CropMode => line.CropMode
}
]
}
]
}
end.to_json],
:headers => { "Content-Type" => "application/json"})
API的请求主体需要如下所示:
"Lines":
[
{
"ProductCode":"5x7",
"Quantity":2,
"UnitPrice":1.25,
"Pages":
[
{
"PageNumber":1,
"Assets":
[
{
"AssetNumber":1,
"Name":"000-R20110419153212.jpg",
"HiResImage":"http:\/\/www.google.com\/xyz.jpg",
"CropMode":"FILLIN"
}
]
}
]
}
]
each
API返回数组本身(无需修改)。您可能希望使用映射
,它返回块结果的数组:
[1, 2, 3].each { |x| x*2 }
# => [1, 2, 3]
[1, 2, 3].map { |x| x*2 }
# => [2, 4, 6]
因此请尝试(您还错过了块中散列结果的大括号的位置):
使用“行”包装器:
HTTParty.post("APIURL",
:body =>
{"Lines" =>
[
@all_lines.map do |line|
{
:ProductCode => line.ProductCode,
:Quantity => line.Quantity,
:UnitPrice => line.UnitPrice,
:Pages =>
[
{
:PageNumber => line.PageNumber,
:Assets =>
[
{
:AssetNumber => line.AssetNumber,
:Name => line.Name,
:HiResImage => line.HiResImage,
:CropMode => line.CropMode
}
]
}
]
}
end]}.to_json,
:headers => { "Content-Type" => "application/json" })
您好,谢谢您的回复!希望你能多帮点忙。我错过了API中的一个结构,我需要在顶部添加行,但我再次遇到语法错误:啊,谢谢!!你能不能也编辑掉Apikey的部分lol,忘了把它取下来
HTTParty.post("APIURL",
:body =>
{"Lines" =>
[
@all_lines.map do |line|
{
:ProductCode => line.ProductCode,
:Quantity => line.Quantity,
:UnitPrice => line.UnitPrice,
:Pages =>
[
{
:PageNumber => line.PageNumber,
:Assets =>
[
{
:AssetNumber => line.AssetNumber,
:Name => line.Name,
:HiResImage => line.HiResImage,
:CropMode => line.CropMode
}
]
}
]
}
end]}.to_json,
:headers => { "Content-Type" => "application/json" })