Ruby on Rails 导入CSV文件至数据库

  •  config/application.rb
require 'csv'
  • view:index.html.erb

Import Products

<%= form_tag import_products_path, multipart: true do %> <%= file_field_tag :file %> <%= submit_tag "Import" %> <% end %>
  • config/routes.rb

Store::Application.routes.draw do
  resources :products do
    collection { post :import }
  end
  root to: 'products#index'
end
  • controller:controllers/products_controller.rb

def import
  Product.import(params[:file])
  redirect_to root_url, notice: "Products imported."
end
  • model: product.rb

def self.import(file)
  CSV.foreach(file.path, headers: true) do |row|
    Product.create! row.to_hash
  end
end
如果想实现修改原来数据的功能,import方法可以写为:

def self.import(file)
  CSV.foreach(file.path, headers: true) do |row|
    product = find_by_id(row["id"]) || new
    product.attributes = row.to_hash.slice(*accessible_attributes)
    product.save!
  end
end

参考链接: http://railscasts.com/episodes/396-importing-csv-and-excel?view=asciicast

源代码:http://media.railscasts.com/assets/episodes/sources/396-importing-csv-and-excel.zip


你可能感兴趣的:(Ruby,on,Rails)