【问题标题】:How do I modify the `params` that were set in the controller in an action?如何修改在控制器中设置的“参数”?
【发布时间】:2023-03-12 22:32:01
【问题描述】:

我将以下参数传递给我的ProfilesController#Update

> profile_params[:videos_attributes]
=> <ActionController::Parameters {"1479585381276"=><ActionController::Parameters {"vimeo_url"=>"https://www.youtube.com/watch?v=Qj2gkjh3-k", "official"=>"false", "_destroy"=>"false"} permitted: true>, "1479585385202"=><ActionController::Parameters {"vimeo_url"=>"https://vimeo.com/some-awesome-video", "official"=>"true", "_destroy"=>"false"} permitted: true>} permitted: true>

我想要做的是删除带有键 1479585381276 的散列(或任何散列)

我尝试使用.delete(key),但这似乎不起作用。

> item
=> "1479585381276"
> profile_params[:videos_attributes].delete(item)
=> <ActionController::Parameters {"vimeo_url"=>"https://www.youtube.com/watch?v=Qas34Pce-k", "official"=>"false", "_destroy"=>"false"} permitted: true>
> profile_params[:videos_attributes]
=> <ActionController::Parameters {"1479585381276"=><ActionController::Parameters {"vimeo_url"=>"https://www.youtube.com/watch?v=Qas34Pce-k", "official"=>"false", "_destroy"=>"false"} permitted: true>, "1479585385202"=><ActionController::Parameters {"vimeo_url"=>"https://vimeo.com/some-awesome-video", "official"=>"true", "_destroy"=>"false"} permitted: true>} permitted: true>

我想这样做的原因是因为当我评估参数时,它仍然会传递给我Profiles#Update 后半部分的@profile.update(profile_params) 并创建一条我不希望它创建的记录。

所以我要做的就是在成功处理后,将其从profile_params[:videos_attributes] 哈希中删除/弹出/删除。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-5 strong-parameters


    【解决方案1】:

    profile_params 每次都会返回一个新的哈希值(带有来自params 的白名单数据的副本)。直接修改params

    params[:profile][:videos_attributes].delete(item)
    

    我以前被这个烫伤过。 :)

    【讨论】:

    • 这是 100% 的钱。非常感谢孟!
    猜你喜欢
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 2019-12-28
    相关资源
    最近更新 更多