我想导入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_counties
,row.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? --- 并认为它可能类似于我想要做的 - 只是不知道如何在这里应用它。
请修改您的问题以包含您正在使用的数据的示例。你说“'row.to_hash'不起作用”,但你忘了说“行”的样子。 –
修改 - 见上文。上面增加了细节。 – user2970050
config/csv/locations/counties.csv文件的一行是什么? –