我正在使用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
任何帮助/线索将不胜感激。
由于在此Importing CSV data into Rails app, using something other then the association "id"提供了一个非常详尽的问题和出色的答案,我设法找到了解决方案>