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:
idstatee.g. "Connecticut"abbreviatione.g. "CT"
My County CSV file has:
idnamee.g. "Hartford"market_statee.g. "Connecticut"
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.
row.to_hashdoes not work" but you forgot to say whatrowlooks like.idfield from the CSV as the models'idattribute or do you want those to be automatically generated by your database? (Unless you know there will never be conflicts with data already in the database, the latter is safer, but if theidfield is significant in some other way you may not want to lose it.)