我传递的JSON对象的数组作为Rails中设置了一个param通过AJAX后/删除,就像保存属性Rails中
[{'id': 3, 'status': true}, {'id': 1, 'status': true}]
我如何遍历params[:list]
得到各ID和状态值?
我传递的JSON对象的数组作为Rails中设置了一个param通过AJAX后/删除,就像保存属性Rails中
[{'id': 3, 'status': true}, {'id': 1, 'status': true}]
我如何遍历params[:list]
得到各ID和状态值?
有两个步骤,这一点,再加上什么@Agis建议。 (感谢@Agis)
我只好先字符串化JSON的:
'p': JSON.stringify(p),
所以它不创造奇怪阵列。有另一个stackoverflow的答案使用这种方法来生成一个正确的数据JSON对象,但它封装了整个数据...我需要这只是p
而不会影响'字符串'安全令牌。 理解这一点从这里:Rails not decoding JSON from jQuery correctly (array becoming a hash with integer keys)
接下来,我不得不使用
ActiveSupport::JSON.decode(params[:p])
从这里一个线索只是PARAM解码:How do I parse JSON with Ruby on Rails?
最后,我可以再使用循环和访问item['id']
尝试类似如下:
params[ :list ][ 0 ][ :id ] # => 3, ...
params[ :list ].each {| v | v[ :id ] } # => 3, 1
在情况下,如果你的哈希就像["0", {"id"=>"9", "status"=>"true"}]
:
# a = ["0", {"id"=>"9", "status"=>"true"}]
h = Hash[[a]]
# => {"0"=>{"id"=>"9", "status"=>"true"}}
,并获得这将是:
h['0'][ :id ] # => '9'
这样做:
params[:list].each do |hash|
hash['id'] # => 3
hash['status'] # => true
end
这不会循环通过每个项目? I.E你不需要遍历'hash'变量? –
谢谢,这是正确的,我发布的答案有这个,也处理为什么事先不能工作的问题。 – bcm
这里有一个循环:
params[:list].each do |item|
item.id
item.satus
end
如果你想创建的id
的数组或东西:
list_ids = params[:list].map(&:id)
在params ...它变成[“0”,{“id”=>“9”,“status”=>“true”}] – bcm
错误:无法将符号转换为整数 – bcm