0

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?

4

1 に答える 1

1

CSVファイルの各行で、前の行に表示されていたすべてのサイトを再作成しています。それがあなたの意図ではないと思います。

答えは、コードの原因となる行をループの外に移動して、リンク配列を終了した後にのみ各サイトを1回だけ作成することです。

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])
  end

  # moved this out
  @hash.keys.each { |key| create_site(key, @hash[key]) }

  flash[:success] = "File imported successfully! Links are currently being processed."
  redirect_to new_import_site_path
end
于 2013-02-14T02:24:12.933 に答える