【问题标题】:Rails CSV Import Duplicating RecordsRails CSV 导入重复记录
【发布时间】:2016-09-16 23:25:38
【问题描述】:

我已经设法在 Rails 4 应用程序上使 CSV 导入工作(基于 this repo)。问题是在我的开发系统上,导入似乎工作正常,但在生产中,所有记录都会重复。请参阅下面的现有代码。任何想法可能导致重复?所有记录仅在 CSV 中出现一次,所有记录都有空白 ID 列,因为我希望系统分配分配。

books_controller.rb

def import
    begin
      Book.import(params[:file])
      redirect_to root_url, notice: "Books imported."
    rescue
     redirect_to root_url, notice: "Invalid CSV file format."
    end
end

def create
  @book = Book.new(book_params)
  @book.save
  save_previews(params[:previews])
  respond_with(@book)
end

def save_previews images
  if images
    images.each_value { |image|
    @book.previews.create(image: image)
    }
  end
end

book.rb

def self.import(file)
  CSV.foreach(file.path, headers: true, :encoding => 'utf-8') do |row|

    product_hash = row.to_hash
    product = Book.where(id: product_hash["id"])

    if product.count == 1
      product.first.update_attributes(product_hash)
    else
      Book.create!(product_hash)
    end # end if !product.nil?
  end # end CSV.foreach
end # end self.import(file)

routes.rb

resources :books do
    get "books/:page", :action => :index, :on => :collection
    resources :comments
    collection do 
      post :import
    end
end

users#show.html.erb

<% if user_signed_in? && current_user.super_admin? %>
  <%= form_tag import_books_path, multipart: true do %>
    <div class="form-group">
      <%= file_field_tag :file %>
      <%= submit_tag "Import CSV", class: "form-control" %>
    </div>
  <% end %>
<% end %>

【问题讨论】:

  • 在您的代码中,保留类定义和诸如此类的东西会很有帮助。例如,我想确保您使用的是活动记录。
  • 我正在使用活动记录是的。

标签: ruby-on-rails ruby csv heroku import


【解决方案1】:

您想使用active record validations 来确保没有重复。这将是uniqueness 验证,以确保只有一条具有该属性的记录。您将需要该属性的范围以将所有其他属性联系在一起。

这是一个简单的例子:

class Book < ActiveRecord::Base
  validates_uniqueness_of :title, scope: :product_id
end

【讨论】:

  • 标题不一定是唯一的。可以有多个产品具有相同的信息(相同的标题、日期、作者、艺术家等),唯一的区别是注释和图像字段。目前,如果我通过管理界面添加单个记录,我可以通过带有回形针的(图像字段)或通过链接(image_remote_url)上传图像,然后在后台使用回形针进行处理。也许我可以这样做: class Book
  • Dbz,很好的建议。我将 image_remote_url 设为唯一字段,它就像收费一样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-03
  • 2018-06-10
  • 1970-01-01
相关资源
最近更新 更多