我有两个 Rails 服务。一个服务于 UI 和一些基本功能 (UIService),另一个管理底层模型和数据库交互 (MainService)。
在 UIService 中,我有一个表单可以收集项目列表并使用它通过 jQuery 发布到 MainService。
我获取 javascript 数组并首先将 jQuery.post 调用到 UIService,就像这样 -
var selected_items = new Array();
// Filled up via the form...
params={"name":$("#name_input").val(),
"items": selected_items };
jQuery.post("/items", params);
然后将其转换为具有键“item_id”的哈希数组,然后像这样通过 Typhoeus 转发到 MainService -
items = []
item = {}
params[:items].each do |i|
item[:item_id] = i
end
## Gives me this ---> items = [ {item_id: 189}, {item_id: 187} ]
req = Typhoeus::Request.new("#{my_url}/items/",
method: :POST,
headers: {"Accepts" => "application/json"})
hydra = Typhoeus::Hydra.new
hydra.queue(req)
hydra.run
在 MainService 中,我需要 JSON 模式采用特定格式。基本上是一系列项目...像这样 -
{ "name": "test_items", "items": [ {"item_id":"189"},{"item_id": "187"} ] }
问题是,当我从 jQuery 收集数组并将其传递给 UIService 时,它在参数中看起来像这样 -
[ {item_id: 189}, {item_id: 187} ]
但是,当它到达 MainService 时,它变成了这个——
{"name"=>"test_items",
"items"=>{"0"=>{"item_id"=>"189"}, "1"=>{"item_id"=>"187"}}
因此,我需要使用“item_id”作为键值并插入到参数中的项目数组。我尝试了几种方法来将它保留为哈希数组,但它总是在目的地以错误的格式结束。
我尝试了各种变通方法,例如字符串化、不字符串化、构建我自己的哈希数组等。我在这一点上很困惑。有任何想法吗?我做错了什么或没有做什么? 我可以让它适用于其他 JSON 模式,但我需要坚持使用这个模式。
最佳答案
问题在于我将参数传递给 typhoeus 的方式
之前(有问题)--
req = Typhoeus::Request.new("#{Rails.application.config.custom_ads_url}/groups",
method: :POST,
params: parameters,
headers: {"Content-Type" => "application/json", "AUTHORIZATION" => "auth_token #{user.auth_token}"})
(作品)之后 -- 请注意,我需要转换为 json 并将其放入正文中。 typhoeus 中的“params”被视为自定义哈希。
req = Typhoeus::Request.new("#{Rails.application.config.custom_ads_url}/groups",
method: :POST,
body: parameters.to_json,
headers: {"Content-Type" => "application/json", "AUTHORIZATION" => "auth_token #{user.auth_token}"})
关于ruby-on-rails - 在带有伤寒的 Rails 应用程序中将哈希数组作为参数传递给 POST 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17101804/