2016-06-08 36 views
1

我想導入2個文件(縣&狀態)。當我導入時,我需要與縣與州之間建立關係。將csv導入到ruby但需要創建關係

我的國家CSV文件:

  • id
  • state例如「Connecticut」
  • abbreviation例如「CT」

我縣CSV文件:

  • id
  • name例如「Hartford」
  • market_state例如「康涅狄格」

爲MarketCounty的屬性有:

create_table "market_counties", force: :cascade do |t| 
    t.string "name" 
    t.integer "market_state_id" 
    t.datetime "created_at",  null: false 
    t.datetime "updated_at",  null: false 
end 

爲MarketState的屬性有:

create_table "market_states", force: :cascade do |t| 
    t.string "name" 
    t.string "abbreviation" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
end 

我的模型有這些關係:

MarketState:

class MarketState < ActiveRecord::Base 
    has_many :market_reports, as: :location 
    has_many :market_cities 
    has_many :market_zips 
    has_many :market_counties 
end 

MarketCounty:

class MarketCounty < ActiveRecord::Base 
    has_many :market_reports, as: :location 
    has_many :market_cities 
    has_many :market_zips 
    belongs_to :market_state 
end 

我的Rake任務:

def import_market_states 
    MarketState.create!(name: "Connecticut", abbreviation: "CT") 
end 

def import_market_counties 
    path = Rails.root.join("config/csv/locations/counties.csv") 
    CSV.foreach(path, headers: true) do |row| 
    MarketCounty.create! row.to_hash 
    end 

我的問題是在方法import_market_countiesrow.to_hash不起作用。

ActiveRecord::AssociationTypeMismatch: MarketState(#70157557268540) 
expected, got String(#70157439770720) 

我手動設置它:

MarketCity.create!(name: "Hartford", market_state: MarketState.find_by(abbreviation: "CT") 

我怎樣才能在一個循環做一個「查找」導入縣文件(把它關聯到MarketState模型)是什麼時候?

爲了澄清,問題是,當我創建縣時,我並不想用CT來填充狀態。我需要用關聯填充state_id。

我發現這個:When importing a CSV, how do I handle data in a row that corresponds to an association? --- 並認爲它可能類似於我想要做的 - 只是不知道如何在這裏應用它。

+0

請修改您的問題以包含您正在使用的數據的示例。你說「'row.to_hash'不起作用」,但你忘了說「行」的樣子。 –

+0

修改 - 見上文。上面增加了細節。 – user2970050

+0

config/csv/locations/counties.csv文件的一行是什麼? –

回答

1

假設你MarketState有一個名稱列,它是國家的名字:

def import_market_counties 


path = Rails.root.join("config/csv/locations/counties.csv") 
    CSV.foreach(path, headers: true) do |row| 
    MarketState.find_by_name(row['market_state'].strip) 
    end 

,如果你要創建的狀態,如果不存在的話,你也可以使用find_or_create_by。

+0

謝謝 - 我會給那一個嘗試......非常感謝。 – user2970050

+0

但後來如何填充縣字段(market_state_id)這是縣領域的協會? – user2970050

+0

因此,創建您的market_county,然後使用Id。 –