Ruby on Rails : API에서 JSON 데이터를 가져와 Postgres 데이터베이스에 저장하려고합니다. 레이크가 중단되었습니다! TypeError : String을 Integer로 암시 적으로 변환하지 않습니다.

존 한론

Ruby on Rails를 사용하고 있으며 공용 API에서 JSON 데이터를 가져와 Postgres 데이터베이스에 저장하려고합니다.

rake db : seed를 실행하면 다음과 같은 오류가 발생합니다.

rake aborted!
TypeError: no implicit conversion of String into Integer
/db/seeds.rb:21:in `[]'
/db/seeds.rb:21:in `properties'
/db/seeds.rb:48:in `<top (required)>'
Tasks: TOP => db:seed
(See full trace by running task with --trace)

참고로 21 행은 다음과 같습니다.

json["data"].map do |property|

48 행은 메소드가 호출되는 곳입니다.

properties

다음은 내가 매핑하려는 항목에 대한 아이디어를 제공하는 JSON 배열의 첫 번째 항목입니다.

[
  {
    "PublicationDate": "26/10/2018",
    "PropertyNumber": 2195606,
    "County": "LAOIS",
    "LocalAuthority": "LAOIS COUNTY COUNCIL",
    "Valuation": 70600.0,
    "Category": "RETAIL (SHOPS)",
    "Uses": "SUPERMARKET 2 [500-2500 SQ. M.], -",
    "Address1": "36-42A/1 POUND STREET",
    "Address2": "RATHDOWNEY",
    "Address3": "CO. LAOIS",
    "Address4": "",
    "Address5": "",
    "CarPark": 0,
    "Xitm": 628016.65,
    "Yitm": 678231.8,
    "ValuationReport": [
      {
        "Level": "0      ",
        "FloorUse": "SUPERMARKET",
        "Area": 964.62,
        "NavPerM2": 60.0000,
        "Nav": 57877.200000
      },
      {
        "Level": "0",
        "FloorUse": "OFF LICENCE",
        "Area": 1.00,
        "NavPerM2": 8681.5800,
        "Nav": 8681.580000
      },
      {
        "Level": "0",
        "FloorUse": "FIT-OUT ALLOWANCE",
        "Area": 1.00,
        "NavPerM2": 4051.4000,
        "Nav": 4051.400000
      }
    ]
  },

내 데이터베이스 스키마는 JSON 구조를 따르지만 정확히는 아닙니다 (이로 인해 문제가 발생하는지 확실하지 않습니다).

create_table "properties", force: :cascade do |t|
    t.bigint "user_id"
    t.string "publication_date"
    t.string "property_number"
    t.string "county"
    t.string "local_authority"
    t.string "valuation"
    t.string "category"
    t.string "uses"
    t.string "address_1"
    t.string "address_2"
    t.string "address_3"
    t.string "address_4"
    t.string "address_5"
    t.string "car_park"
    t.string "xitm"
    t.string "yitm"
    t.string "valuation_report"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["user_id"], name: "index_properties_on_user_id"
  end 

다음은 내 seed.rb 파일입니다.

require 'rest-client'

# Define Method
def properties

    response = RestClient.get('https://api.valoff.ie/api/Property/GetProperties?Fields=*&LocalAuthority=LAOIS%20COUNTY%20COUNCIL&CategorySelected=RETAIL%20(SHOPS)&Format=csv&Download=false')

    json = JSON.parse response
    
    if !json.nil?
        json["data"].map do |property|
            Property.create(
                publication_date: "#{PublicationDate}",
                property_number: "#{PropertyNumber}",
                county: "#{County}",
                local_authority: "#{LocalAuthority}",
                valuation: "#{Valuation}",
                category: "#{Category}",
                uses: "#{Uses}",
                address_1: "#{Address1}",
                address_2: "#{Address2}",
                address_3: "#{Address3}",
                address_4: "#{Address4}",
                address_5: "#{Address5}",
                car_park: "#{CarPark}",
                xitm: "#{Xitm}",
                yitm: "#{Yitm}",
                valuation_report: "#{ValuationReport}"
            )
        end
    else
        puts "Error seeding properties."
    end

end

# Call Method
properties

rake db : seed를 실행하면 다음과 같은 오류가 발생합니다.

rake aborted!
TypeError: no implicit conversion of String into Integer
/db/seeds.rb:21:in `[]'
/db/seeds.rb:21:in `properties'
/db/seeds.rb:48:in `<top (required)>'
Tasks: TOP => db:seed
(See full trace by running task with --trace)

참고로 21 행은 다음과 같습니다.

json["data"].map do |property|

48 행은 메소드가 호출되는 곳입니다.

properties

어떤 도움을 주시면 감사하겠습니다.

rmlockerd

다양한 의견의 권장 사항을 요약하면, json입니다 Arrayjson으로 구문 분석 후. 배열 인덱스는 그래서 정수 json["data"]A의 결과 TypeError. 둘째, data반환 된 JSON 레코드에 대한 필드 가 없습니다 . 결과 배열을 간단히 반복하고 다음과 같이 레코드를 만들 수 있습니다.

def properties
  response = RestClient.get('https://api.valoff.ie/api/Property/GetProperties?Fields=*&LocalAuthority=LAOIS%20COUNTY%20COUNCIL&CategorySelected=RETAIL%20(SHOPS)&Format=csv&Download=false')

  json = JSON.parse(response)

  json.each do |property|
    puts "Creating property #{property['PropertyNumber']}"
    Property.create!(
      publication_date: property['PublicationDate'],
      property_number: property['PropertyNumber'],
      county: property['County'],
      local_authority: property['LocalAuthority'],
      valuation_report: property['ValuationReport']
      # ... remaining fields omitted for brevity
    )
  end
end

200-2007 이외의 HTTP 응답 코드에 대해 오류가 발생하기 .nil?때문에 원본을 확인할 필요가 없습니다 RestClient. 마찬가지로 JSON.parse응답이 유효한 JSON이 아닌 경우 오류가 발생합니다.

결과:

$ rails db:seed
Creating property 1555903
Creating property 1556133
Creating property 1556998
Creating property 1556516
Creating property 1557007
...

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관