Ruby 如何为grape创建对象数组
我正在为rails应用程序使用GrapeAPI构建Api 我现在尝试的是以下表格: 这就是输出:Ruby 如何为grape创建对象数组,ruby,rest,parameters,grape,grape-api,Ruby,Rest,Parameters,Grape,Grape Api,我正在为rails应用程序使用GrapeAPI构建Api 我现在尝试的是以下表格: 这就是输出: { "page_score_master": { "issue_date": "2014-06-23" }, "press_id": "1", "print_date": "2014-06-23", "product_id": 1, "pull_id": 2, "press_run_id": 1, "total_sect
{
"page_score_master": {
"issue_date": "2014-06-23"
},
"press_id": "1",
"print_date": "2014-06-23",
"product_id": 1,
"pull_id": 2,
"press_run_id": 1,
"total_section": 1,
"ssa": [
{
"ss": {
"section_name": "A"
},
"ss1": {
"section_name": "B"
}
}
],
"foreman_id": 1,
"pic_id": 1,
"score_sheet_master_id": 1,
"score_sheet_sections_attributes": {
"score_sheet_id": "1"
},
"route_info": {
"options": {
"description": "create score sheet",
"params": {
"page_score_master": {
"required": true,
"type": "Hash"
},
"page_score_master[issue_date]": {
"required": true,
"type": "String"
},
"print_date": {
"required": true,
"type": "String"
},
"total_section": {
"required": true,
"type": "Integer"
},
"ssa": {
"required": false,
"type": "Array"
},
"ssa[section_name]": {
"required": false,
"type": "String"
},
"ssa[total_pages]": {
"required": false,
"type": "Integer"
},
"ssa[color_pages]": {
"required": false,
"type": "String"
},
"ssa[score_sheet_id]": {
"required": false,
"type": "Integer"
}
}
}
我省略了json的某些部分以使其更简短
我需要的是有一个数组或ssa
,但不知何故直到现在都无法实现。它只使用一个对象生成一个ssa
数组
在API控制器中,我有以下代码:
optional :ssa, type: Array do
requires :ss, type: Hash do
optional :section_name, type: String
optional :total_pages, type: Integer
optional :color_pages, type: String
optional :score_sheet_id, type: Integer
end
end
我想你有两个问题。 第一个是你们的申报表。 在代码中,您说您有一个散列数组(称为
ssa
)(称为ss
)。
在表单中,您将发送一个名为ss1
的散列,作为“ssa”数组的一部分。ss1
散列将被忽略,因此数组中只有一个“ss”元素
如果以您的格式将ss1
重命名为ss
:
ssa[][ss][section_name] A
ssa[][ss][section_name] B
您将看到第二个问题,它存在于API控制器定义中:
控制器需要一个“ssa”数组,该数组只能有一个“ss”哈希元素。因此,它将覆盖第一个[ss][section\u name]
您要做的是将ssa
声明为一个数组,并删除ss
组:
requires :ssa, type: Array do
optional :section_name, type: String
optional :total_pages, type: Integer
optional :color_pages, type: String
optional :score_sheet_id, type: Integer
end
这将需要一个散列数组(ssa
)。您不需要声明ss
组,它已经需要一个散列数组,其中节名
,总页数
等作为键。如果ssa
不是必需的参数,只需将其声明为可选
,就像您在控制器中所做的那样。
然后,您的表单应该如下所示:
ssa[][section_name] ABC
opportunity[ssa][][total_pages] 3
ssa[][section_name] DEF
opportunity[ssa][][total_pages] 6
这将导致:
:ssa=>
[{:section_name=>"DEF",
:total_pages=>3,
:color_pages=>nil,
:score_sheet_id=>nil},
{:section_name=>"HGJK",
:total_pages=>6,
:color_pages=>nil,
:score_sheet_id=>nil}]
你试过这个吗?