2014-01-29 149 views
0

我傳遞的JSON對象的數組作爲Rails中設置了一個param通過AJAX後/刪除,就像保存屬性Rails中

[{'id': 3, 'status': true}, {'id': 1, 'status': true}] 

我如何遍歷params[:list]得到各ID和狀態值?

+0

在params ...它變成[「0」,{「id」=>「9」,「status」=>「true」}] – bcm

+0

錯誤:無法將符號轉換爲整數 – bcm

回答

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]) 

從這裏一個線索只是PARAM解碼:How do I parse JSON with Ruby on Rails?

最後,我可以再使用循環和訪問item['id']

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' 
+0

試過..我得到一個錯誤不能轉化ert符號轉換爲整數 – bcm

+0

@bcm轉儲'params [:list] [0] .inspect' –

+0

@bcm我已更新答案 –

0

這樣做:

params[:list].each do |hash| 
    hash['id'] # => 3 
    hash['status'] # => true 
end 
+0

這不會循環通過每個項目? I.E你不需要遍歷'hash'變量? –

+0

謝謝,這是正確的,我發佈的答案有這個,也處理爲什麼事先不能工作的問題。 – bcm

-1

這裏有一個循環:

params[:list].each do |item| 
    item.id 
    item.satus 
end 

如果你想創建的id的數組或東西:

list_ids = params[:list].map(&:id)