加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 为什么Rails参数包装不包含来自URI的全局内容

发布时间:2020-12-17 04:32:38 所属栏目:百科 来源:网络整理
导读: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给出
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 has_many Bs;因此B具有外键a_id.

你使用空载荷POST / as / 1 / bs(因为B没有其他字段).假设a_id是attr_accessible,可以假设a_id将包装在b对象中.相反,你会看到:

Processing by BsController#create as HTML
  Parameters: {"b"=>{},"a_id" => "1"}

没有这样的运气.事实证明,ParamsWrapper uses request_parameters而不是params,因此在POST有效载荷中不包括a_id意味着它不会被包裹.这是非常令人困惑的,因为你仍然看到它包含在params中,由于URI globbing,并且想知道为什么它被排除在所有东西之外.

有没有什么好的理由在这里使用request_parameters而不是params?

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

tl; dr:ParamsWrapper使用request_parameters作为参数源,因此跳过了URI-globbed变量.这是一个Rails错误吗?纯REST倡导者可能会说不,但实用主义暗示是.

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读