user2970050
user2970050

Reputation: 307

importing csv into ruby but need to create relationship

I am wanting to import 2 files (County & State). When I import I need to create a relationship with County to State.

My State CSV file has:

My County CSV file has:

The attributes for MarketCounty are:

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

The attributes for MarketState are:

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

My models have these relationships:

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

My Rake task:

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

My question is in the the method import_market_counties, row.to_hash does not work.

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

I set it up manually:

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

How can I do a "lookup" in a loop when importing County file (to associate it to the MarketState model)?

To clarify, the issue is that when I am creating the County, I am not trying to populate state with CT. I need to populate state_id with the association.

I found this SO: When importing a CSV, how do I handle data in a row that corresponds to an association? --- And thinking it may be similar to what I am trying to do - just not sure how to apply it here.

Upvotes: 1

Views: 290

Answers (1)

ruby_newbie
ruby_newbie

Reputation: 3285

Assuming your MarketState has a name column that is the name of the state:

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

you can also use find_or_create_by if you want to create the state if it doesn't exist.

Upvotes: 1

Related Questions