0

我正在使用gem roo导入 CSV 数据。它工作顺利,直到存在关联,并且希望 roo 可以将字符串转换为关联中相应的整数值。就我而言,我有一个Staff属于State.

class State < ApplicationRecord
    has_many :staffs

end
class Staff < ApplicationRecord
    belongs_to :state

end

这意味着我state_id在表中有列staffs。然而,在我的 CSV 中,最终用户拥有与states表格中的状态相对应的状态名称。当我尝试导入 CSV 时,出现错误:

ActiveRecord::AssociationTypeMismatch in StaffsImportsController#create
State(#134576500) expected, got "Texas" which is an instance of String(#20512180)

突出显示的来源是:

staff.attributes = row.to_hash

是否可以gem roo将 csv 文件中的“Texas”翻译为 id 2,而不是最终用户在上传数据之前进行大量翻译工作?

这是staffs_imports.rb

class StaffsImport
  include ActiveModel::Model
  require 'roo'

  attr_accessor :file

  def initialize(attributes={})
    attributes.each { |name, value| send("#{name}=", value) }
  end

  def persisted?
    false
  end

  def open_spreadsheet
    case File.extname(file.original_filename)
    when ".csv" then Csv.new(file.path, nil, :ignore)
    when ".xls" then Roo::Excel.new(file.path, nil, :ignore)
    when ".xlsx" then Roo::Excelx.new(file.path)
    else raise "Unknown file type: #{file.original_filename}"
    end
  end

  def load_imported_staffs
    spreadsheet = open_spreadsheet
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).map do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      staff = Staff.find_by_national_id(row["national_id"]) || Staff.new
      staff.attributes = row.to_hash
      staff
    end
  end

  def imported_staffs
    @imported_staffs ||= load_imported_staffs
  end

  def save
    if imported_staffs.map(&:valid?).all?
      imported_staffs.each(&:save!)
      true
    else
      imported_staffs.each_with_index do |staff, index|
        staff.errors.full_messages.each do |msg|
          errors.add :base, "Row #{index + 6}: #{msg}"
        end
      end
      false
    end
  end

end

最后是staff_imports_controller.rb

class StaffsImportsController < ApplicationController

  def new
    @staffs_import = StaffsImport.new
  end

  def create
    @staffs_import = StaffsImport.new(params[:staffs_import])
    if @staffs_import.save
      flash[:success] = "You have successfully uploaded your staff!"
      redirect_to staffs_path
    else
      render :new
    end
  end
end

任何帮助/线索将不胜感激。

4

1 回答 1

0

我设法解决了这个问题,这要归功于此处提供的一个非常详细的问题和很好的答案Importing CSV data into Rails app, using other than the association "id"

于 2019-10-04T08:29:39.223 回答