在我的Rails控制器中,我發佈了包含人員工作歷史記錄的JSON。所以他們可以有多個工作。該工作是在一個格式像...如何爲params散列創建數組
"values":
[
{
"title": "dummy position",
"company": "company 1",
"location": "Indianapolis, IN",
"description": "dummy job description",
"startDateMonth": "05",
"startDateYear": "2015",
"endDateMonth": "06",
"endDateYear": "2015"
},
{
"title": "dummy position 2",
"company": "company 2",
"location": "Indianapolis, IN",
"description": "dummy job description 2",
"startDateMonth": "02",
"startDateYear": "2015",
"endDateMonth": "05",
"endDateYear": "2015"
},
{
"title": "dummy position 3",
"company": "company 3",
"location": "Indianapolis, IN",
"description": "dummy job description 3",
"startDateMonth": "05",
"startDateYear": "2013",
"endDateMonth": "02",
"endDateYear": "2015"
}
]
我想這些內容添加到PARAMS集合以後我可以通過一個應用程序類迭代,並添加這些工作經歷。我有下面的代碼,但它不起作用 - NoMethodError - 未定義的方法`[]'nil:NilClass:對於這一行params [:job_title] [i] = jobs [i] ['title']。這只是一個猜測,因爲我在紅寶石方面不是很出色,所以有什麼辦法可以做到這一點?
if job_count.numeric?
jobs = params['positions']['values']
for i in 0..job_count.to_i
params[:job_title][i] = jobs[i]['title']
params[:job_company_name][i] = jobs[i]['company']
params[:job_start_date][i] = jobs[i]['startDateMonth'] + '/1/' + jobs[i]['startDateYear']
params[:job_end_date][i] = jobs[i]['endDateMonth'] + '/1/' + jobs[i]['endDateYear']
params[:job_description][i] = jobs[i]['description']
end
end
編輯:這結束了工作。
i = 0
jobs.each do | k, work_history |
i = i + 1
params['job_title_' + i.to_s] = work_history['title']
params['job_company_name_' + i.to_s] = work_history['company']
params['job_start_date_' + i.to_s] = work_history['startDateMonth'] + '/1/' + work_history['startDateYear']
params['job_end_date_' + i.to_s] = work_history['endDateMonth'] + '/1/' + work_history['endDateYear']
params['job_description_' + i.to_s] = work_history['description']
end
params哈希表正是從post數據到控制器中來。我可以像params [:new_value] ='foo'那樣向散列添加其他參數,但是我不確定如何在params散列中獲得數組結構。 –
因爲我正在將JSON發佈到我的控制器操作中,該操作在其中擁有大量的數據。不要粗魯,但我不明白這對問題有什麼影響。 –
我覺得我很接近它,但我發現Nil類錯誤正在爲[i] ['title']作業發生,所以我沒有正確引用它。如果我做了一個工作,我會得到以下結果。 「jobtitle {\」0 \「=> {\」title \「=> \」dummy position \「,\」company \「=> \」company 1 \「,\」location \「=> \」Indianapolis, IN \「,\」description \「=> \」dummy job description \「,\」startDateMonth \「=> \」05 \「,\」startDateYear \「=> \」2015 \「,\」endDateMonth \「 => \「06 \」,\「endDateYear \」=> \「2015 \」},\「1 \」=> {\「title \」=> \「dummy position 2 \作業變量有一個值,但是我怎樣迭代每一個? –