就地修改 ruby​​ 哈希(rails strong params) [英] Modify ruby hash in place( rails strong params)

查看:35
本文介绍了就地修改 ruby​​ 哈希(rails strong params)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能更像是一个 ruby​​ 问题,而不是 rails 问题,但我很确定我能够在 vanilla ruby​​ 应用程序中做到这一点.

This may be more a ruby question then rails question but I'm pretty sure I was able to do this in a vanilla ruby application.

我定义了强参数.

def trip_params
  params.require(:trip).permit(:name, :date)
end

现在我在控制器方法中获取这些参数.我想这样做.

Now I get those params in a controller method. I want to do this.

def save
  trip_params[:name] = 'Modifying name in place'
  #trip_params[:name] still equals original value passed
end

这永远行不通.名称永远不会改变.顺便说一句:trip_params 的类型是 ActionController::Parameters

This never works. Name never changes. BTW: The type of trip_params is ActionController::Parameters

如果我执行标准的 ruby​​ 脚本,它就可以工作.

If I do a standard ruby script, it works.

test = {}    
test[:name] = "blah"    
test[:name] = "ok"    
puts test #{:name=>"ok"}

推荐答案

permit 返回包含这些键的新散列,因此您不会修改真正的 params 变量.您也没有保存对散列 trip_params 返回的引用,因此您在 save 中的每次调用都会得到它.

permit returns a new hash with those keys in it, so you're not modifying the real params variable. You're also not saving a reference to the hash trip_params returns, so you get it fresh each call in save.

试试这个:

def save
  tp = trip_params
  tp[:name] = 'Modifying name in place'
  # ... use tp later, it'll be in there
end

或者,如果您真的希望像以前那样使用它,请像这样修改 trip_params:

Or, if you really want it to be used the way you previously did, modify trip_params like so:

def trip_params
  @trip_params ||= params.require(:trip).permit(:name, :date)
end

现在哈希被延迟缓存,并且在后续的 trip_params 调用中返回相同的哈希.

Now that hash is lazily cached and the same one is returned on subsequent trip_params calls.

这篇关于就地修改 ruby​​ 哈希(rails strong params)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆