英文:
Grape API malformed parameters
问题
I'm trying to make a post endpoint, with multiple nested parameters but the params are not as expected
I have the following parameters definitions for the endpoint:
params do
requires :p2 do
optional :p3
requires :p4, as: :p4_new
requires :p5, as: :p5_new do
requires :p6, as: :p6_new
end
end
end
So I put a debugger in the first line of the endpoint and I am expecting the parameters to look like this:
{
"p2": {
"p3": 1,
"p4_new": "Ceva nume",
"p5_new": {
"p6_new": 1
}
}
}
But the actual parameters are malformed, it gives me both the newly named parameters and the old name for the parameters, in a chaotic order. It doesn't make any sense. Does anyone know what is going on here?
英文:
I'm trying to make a post endpoint, with multiple nested parameters but the params are not as expected
I have the following parameters definitions for the endpoint:
params do
requires :p2 do
optional :p3
requires :p4, as: :p4_new
requires :p5, as: :p5_new do
requires :p6, as: :p6_new
end
end
end
So I put a debugger in the first line of the endpoint and I am expecting the parameters to look like this:
{
"p2": {
"p3": 1,
"p4_new": "Ceva nume",
"p5_new": {
"p6_new": 1,
}
}
}
But the actual parameters are malformed, it gives me both the newly named parameters and the old name for the parameters, in a chaotic order.
It doesn't make any sense. Does anyone know what is going on here?
答案1
得分: 1
你看到了params
和declared(params)
之间的区别。有关重命名参数的文档指定,如果您只想要重命名后的参数,您需要使用declared(params)
:
您可以使用
as
来重命名参数,这在重构现有API时非常有用:
resource :users do
params do
requires :email_address, as: :email
requires :password
end
post do
User.create!(declared(params)) # User接受email和password
end
end
传递给
as
的值将在调用declared(params)
时成为键。
我假设您正在调用params
,这会将原始参数和重命名后的参数合并在一起。切换到declared(params)
以获取只有重命名后的参数。
英文:
You're seeing the difference between params
and declared(params)
. The documentation on renaming params specifies that if you want only the renamed parameters that you need to use declared(params)
:
> You can rename parameters using as
, which can be useful when refactoring existing APIs:
resource :users do
params do
requires :email_address, as: :email
requires :password
end
post do
User.create!(declared(params)) # User takes email and password
end
end
> The value passed to as
will be the key when calling declared(params)
I assume that you're calling params
which is giving you both the original and the renamed parameters merged together. Switch to declared(params)
to get just the renamed parameters.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论