如何将文件名添加为数据库中的新列?

时间:2015-03-10 14:59:04

标签: ruby-on-rails ruby

我使用RailsCast剧集#396导入CSV和Excel,这非常有用。

现在我想在每一行添加一个带有文件名的新列(文件名)。 我知道我需要创建一个带有新迁移的新表。

system.rb:

class System < ActiveRecord::Base


def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
    row = Hash[[header, spreadsheet.row(i)].transpose]

    system = find_by_id(row["id"]) || new
    system.attributes = row.to_hash.slice(*System.attribute_names())
    system.save!
  end
end

def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::Csv.new(file.path.encode!("UTF-8", "Cp437"), csv_options: {col_sep: "\;"})             #, csv_options: {encoding: Encoding::ISO_8859_1})
 # when ".xls" then Excel.new(file.path, nil, :ignore)
 # when ".xlsx" then Excelx.new(file.path, nil, :ignore)
  else raise "Unknown file type: #{file.original_filename}"
  end
end


end

controller.rb:

class SystemsController < ApplicationController
  before_action :set_system, only: [:show, :edit, :update, :destroy, ]

  # GET /systems
  # GET /systems.json
  def index
    @systems = System.all
    db = SQLite3::Database.new './db/development.sqlite3' 
    @datens = db.execute 'SELECT ID1, ID2 FROM systems'
  end



def import
  System.import(params[:file])
  redirect_to root_url, notice: "yeah"
end

index.html.erb:

<%= form_tag import_systems_path, multipart: true do %>
  <%= file_field_tag :file %>
  <%=  %>
  <%= submit_tag "read" %>
<% end %>

1 个答案:

答案 0 :(得分:0)

def self.import(file)
  file_name = File.basename(file)
  row = Hash[[header, spreadsheet.row(i)].transpose].merge({:file_name => file_name})
OR
  row.to_hash.slice(*System.attribute_names()).merge({:file_name => file_name})
end

在self.import(file)中添加这些行,假设您已经运行了迁移并添加了file_name字段。