How to create array for params hash

时间:2015-06-30 13:59:55

标签: ruby-on-rails

In my rails controller I'm getting JSON posted to it that contains a person's work history. So they could have multiple jobs. The jobs are in a format like...

"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"
  }
]

I'm trying to add these to the params collection that I can later iterate through in an application class and add these work histories. I have the following code but it doesn't work - NoMethodError - undefined method `[]' for nil:NilClass: for this line params[:job_title][i] = jobs[i]['title']. It was just a guess, as I'm not great in ruby, so is there a way to make this work?

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

EDIT: This ended up working.

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

1 个答案:

答案 0 :(得分:0)

您收到此错误是因为您正在尝试在["title"] nil上执行jobs[i],而nil可能是job_count,因为job_count == 3是错的。

如果您有3个职位和for,则jobs[3]循环将执行0,1,2,3。但是,for i in 0..(job_count.to_i - 1)是正确的。

尝试将其替换为 All interface orientations must be supported unless the app requires full screen. A launch storyboard or xib must be provided unless the app requires full screen.