0

我正在尝试向我的应用程序添加“通过 CSV 导入”功能。我一直在玩弄代码来弄清楚它是如何工作的。在我的应用程序 aUser has_many :websites和 aWebsite has_many :links中。这是我目前拥有的:

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

该代码正在生成正确的哈希,例如:

{"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"}]}

如果我使用上面的哈希在 Rails 控制台中运行代码,它只会按预期创建 2 个网站和 3 个链接,但是在我的应用程序中它会创建 5 个网站和 6 个链接:

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

我究竟做错了什么?

4

1 回答 1

1

对于 CSV 文件中的每一行,您都在重新创建在前几行中看到的所有网站。我不认为这是你的意图。

答案是将罪魁祸首的代码行移出循环,以便您只在完成链接数组之后才创建每个站点一次。

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 回答