【发布时间】: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