Rails4:如何在参数中允许带有动态键的哈希? [英] Rails4: How to permit a hash with dynamic keys in params?

查看:33
本文介绍了Rails4:如何在参数中允许带有动态键的哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下参数发出 http put 请求:

I make a http put request with following parameters:

{"post"=>{"files"=>{"file1"=>"file_content_1","file2"=>"file_content_2"}}, "id"=>"4"}

{"post"=>{"files"=>{"file1"=>"file_content_1", "file2"=>"file_content_2"}}, "id"=>"4"}

而且我需要在我的代码中允许哈希数组.基于 手册 我试过这样的:

and i need to permit hash array in my code. based on manuals I've tried like these:

> params.require(:post).permit(:files) # does not work
> params.require(:post).permit(:files => {}) # does not work, empty hash as result
> params.require(:post).permit! # works, but all params are enabled

如何正确制作?

UPD1:file1、file2 - 是动态密钥

UPD1: file1, file2 - are dynamic keys

推荐答案

Rails 5.1+

params.require(:post).permit(:files => {})

Rails 5

params.require(:post).tap do |whitelisted|
  whitelisted[:files] = params[:post][:files].permit!
end

Rails 4 及以下

params.require(:post).tap do |whitelisted|
  whitelisted[:files] = params[:post][:files]
end

这篇关于Rails4:如何在参数中允许带有动态键的哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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