导入csv行时我需要检查这是重复条目还是新条目。 我的csv看起来像这样,
company,location,region,service,price,duration,disabled
Google,Berlin,EU,Design with HTML/CSS,120,30,false
Google,San Francisco,US,Design with HTML/CSS,120,30,false
Google,San Francisco,US,Restful API design,1500,120,false
Apple,London,EU,Design with HTML/CSS,120,30,false
Google,Berlin,EU,Design with HTML/CSS,120,30,false
Google,San Francisco,US,Restful API design,1500,120,false
此外,行值应导入到其关联类似
的不同表中公司:
服务:
我已经实现了像这样的协会
class Company < ApplicationRecord
has_many :regions
has_many :services
has_many :locations, through: :regions
end
class Region < ApplicationRecord
belongs_to :company
has_many :locations
end
class Location < ApplicationRecord
belongs_to :region
belongs_to :company
end
class Service < ApplicationRecord
belongs_to :company
end
我将如何导入?
我正在做这样的事情
namespace :import do
desc "Import data"
task company: :environment do
CSV.foreach('lib/data/companies_data.csv', headers:true) do |row|
company = Company.create(:name => row["company"])
region = company.regions.create(:name => row["region"])
if region.id and company.id
location = company.locations.create(:name =>row["location"],
:region_id => region.id)
service = company.services.create(:name => row["service"],
:price => row["price"], :duration =>
row["duration"], :disabled =>row["disabled"])
end
end
end
end
如何检查数据库中是否已存在一行,因为它已包含关联的表。
答案 0 :(得分:0)
您可以使用.first_or_create。如果以前的ActiveRecord Relation调用没有匹配,则只会创建新的db记录:
Model.where(some_unique_field: row['Unique Column']).first_or_create(row)
如果您想将任何其他逻辑应用于CSV行,即model.price = row['price'] + fee