我通过AJAX帖子/删除传递作为Rails中的参数的JSON对象数组,如
[{'id': 3, 'status': true}, {'id': 1, 'status': true}]
如何遍历params[:list]
以获取每个ID和状态值?
答案 0 :(得分:0)
尝试如下:
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'
答案 1 :(得分:0)
这样做:
params[:list].each do |hash|
hash['id'] # => 3
hash['status'] # => true
end
答案 2 :(得分:0)
这有两个步骤,加上@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])
来自此处的线索:How do I parse JSON with Ruby on Rails?
最后,我可以使用循环并访问item['id']
答案 3 :(得分:-1)
这是一个循环:
params[:list].each do |item|
item.id
item.satus
end
如果你想创建一个id
或其他的数组:
list_ids = params[:list].map(&:id)