gpt4 book ai didi

ruby-on-rails - 为什么 Rails 参数包装不包括从 URI 中获取的内容?

转载 作者:行者123 更新时间:2023-12-04 08:55:56 26 4
gpt4 key购买 nike

docs on parameter wrapping状态:

Wraps the parameters hash into a nested hash. This will allow clients to submit POST requests without having to specify any root elements.



它有助于省略哪些参数散列被包装。 Action Controller overview guide给出了这个破败:

Rails collects all of the parameters sent along with the request in the params hash, whether they are sent as part of the query string or the post body. […] The query_parameters hash contains parameters that were sent as part of the query string while the request_parameters hash contains parameters sent as part of the post body. The path_parameters hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action.



当您使用 RESTful 资源和路由时,乐趣就会发生。假设你有一个模型 A,它有_many Bs; B 因此有一个外键 a_id .

POST /as/1/bs负载为空(因为 B 没有其他字段)。假设 a_idattr_accessible ,人们可能会假设 a_id将被包裹在 b 中目的。相反,您会看到:
Processing by BsController#create as HTML
Parameters: {"b"=>{}, "a_id" => "1"}

没有这样的运气。原来 ParamsWrapper uses request_parameters 而不是 params ,所以不包括 a_id在 POST 有效载荷中意味着它没有被包装。这很令人困惑,因为您仍然看到它包含在 params 中。 ,由于 URI globbing,并想知道为什么它被排除在所有事物之外。

是否有充分的理由使用 request_parameters而不是 params这里?

我可以理解,从“REST 哲学”的角度来看,如果我们假设有效负载包含整个对象会更纯粹,但这实质上意味着 a_id在 URI 中完全被忽略,这似乎很可惜。

tl;博士: ParamsWrapper用途 request_parameters作为参数源,因此跳过 URI 全局变量。这是一个Rails错误吗?纯粹的 REST 拥护者可能会说不,但实用主义建议是。

最佳答案

据我了解,a_id 未包含在 'b' 的哈希中的原因是我们需要该 id 值来首先检查该记录是否存在于我们的数据库中。这样,我们可以简单地拒绝请求中的其他参数。根据不将其包含在 'b' 哈希中的原因:它可以防止事故。考虑这个场景:假设有人正在更新表单并将完整的“b”哈希作为参数传递给模型对象。现在,当我们调用 model_object.save 时,它​​可能会将记录保存在我们的数据库中,而不是更新旧记录,这将是一个安全威胁(如果对象已提前初始化,则可能发生)。不是一个完全证明的场景,但在编码时确实会发生事故,它可以帮助我们防止此类事故。

关于ruby-on-rails - 为什么 Rails 参数包装不包括从 URI 中获取的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12066607/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com