Rails 4 - 使用scaffold的强参数 - params.fetch

Mel*_*Mel 6 controller ruby-on-rails scaffolding strong-parameters

我使用scaffold命令在我的Rails 4应用程序中制作我的组件.

最近,设置强params的方法中使用的术语已经从params.require变为params.fetch,现在设置中有花括号.

private
    # Never trust parameters from the scary internet, only allow the white list through.
    def engagement_params
      params.fetch(:engagement, {})
    end
Run Code Online (Sandbox Code Playgroud)

我找不到任何解释变更或如何使用它的文档.

我还可以将params.fetch(:engagement).permit(:opinion)写入fetch命令吗?我不知道如何处理花括号.

如何使用这种新的表达方式完成强大的参数?

Dee*_*ale 5

我从未遇到过这种情况,但在这里,我找到了fetch方法的参考

http://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-fetch

我还可以将params.fetch(:engagement).permit(:opinion)写入fetch命令吗?

是的,你仍然可以使用

params.fetch(:engagement).permit(:attributes, :you, :want, :to, :allow)
Run Code Online (Sandbox Code Playgroud)

我不知道如何处理花括号.

它是一个默认值,如果key不存在则将返回该值,否则将引发错误

params.fetch(:engagement)
#=> *** ActionController::ParameterMissing Exception: param is missing or the value is empty: engagement

params.fetch(:engagement, {})
#=> {}

params.fetch(:engagement, 'Francesco')
#=> 'Francesco'
Run Code Online (Sandbox Code Playgroud)

如何使用这种新的表达方式完成强大的参数?

params.fetch(:engagement).permit(:attributes, :you, :want, :to, :allow)
Run Code Online (Sandbox Code Playgroud)

  • @Mel,如果参数中没有 key :engagement,它将返回空哈希。检查上面我已经编辑了答案 (2认同)