I'm trying to add an 'import via CSV' function to my app. I've been playing around with the code to figure out how it works. In my app a User has_many :websites
and a Website has_many :links
. This is what I have currently:
def create
file = params[:file]
@hash = {}
CSV.foreach(file.path, headers: true) do |row|
hash = row.to_hash.slice("link", "project", "comment", "email")
site = row["website"]
@hash.has_key?(site) ? @hash[site] << hash : @hash.merge!(site => [hash])
@hash.keys.each { |key| create_site(key, @hash[key]) }
end
flash[:success] = "File imported successfully! Links are currently being processed."
redirect_to new_import_site_path
end
private
def create_site(site_link, links_array)
website = current_user.websites.build(link: site_link)
links_array.each do |link|
website.links.build(page: link["link"], validation_id: current_user.id)
end
website.save
end
The code is generating the correct hash, e.g:
{"http://google.com"=>[{"link"=>"http://stackoverflow.com", "project"=>"Test", "comment"=>"this is a comment", "email"=>"email@gmail.com"}, {"link"=>"http://golf.com", "project"=>nil, "comment"=>"this is a comment", "email"=>"email@gmail.com"}], "http://yahoo.com"=>[{"link"=>"http://bing.com", "project"=>"Test", "comment"=>"this is a comment", "email"=>"email@gmail.com"}]}
If I run the code in my rails console using the hash above it creates only 2 websites and 3 links as expected, however in my app it creates 5 websites and 6 links:
Website ID Associated Link ID
http://yahoo.com | 406 http://bing.com | 1223
http://google.com | 405 http://golf.com | 1222
http://google.com | 405 http://stackoverflow.com | 1221
http://yahoo.com | 404 http://bing.com | 1220
http://google.com | 403 http://stackoverflow.com | 1219
http://google.com | 402 http://stackoverflow.com | 1218
What am I doing wrong?