簡體   English   中英

遍歷軌道中的哈希數組

[英]Loop through array of hashes in rails

我將以下哈希數組發送給控制器:

comparisons = [{
  "startdate": "01/01/2016",
  "enddate": "01/02/2016"
}, {
  "startdate": "01/03/2016",
  "enddate": "01/04/2016"
}, {
  "startdate": "01/05/2016",
  "enddate": "01/06/2016"
}, {
  "startdate": "01/05/2016",
  "enddate": "01/06/2016"
}];

$.ajax({
  url: '/get_data',
  method: 'GET',
  dataType: 'JSON',
  data: {
    startdate: '01/01/2016',
    enddate: '01/01/2016',
    comparisons: comparisons
  },
  success: function (data) {
    console.log(data);
  }
});

然后在控制器中,我想遍歷這些比較:

@comparisons = []
if !params[:comparisons].blank?
  params[:comparisons].each do |c|
    @comparisons.push({:startdate => c[:startdate], :enddate => c[:enddate], :data => get_data(c[:startdate], c[:enddate], 'week')})
  end
end

我收到一個錯誤: > no implicit conversion of Symbol into Integer

而且在調試時,我發現循環中的c與發送的結構不同...

c: ["0", {"startdate"=>"01/01/2016", "enddate"=>"01/01/2016"}]

我怎樣才能解決這個問題?

最簡單的解決方法是更改​​引用c數據的方式...您可以看到c是一個數組(解釋了錯誤,它期望數組元素可以通過整數訪問),並且可以看到第二個(最后一個)元素c數組中的數據具有所需的數據。

@comparisons.push({:startdate => c.last[:startdate], 
                   :enddate => c.last[:enddate], 
                   :data => get_data(c.last[:startdate], c.last[:enddate], 'week')})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM