Ruby on rails 如何从excel文件导入关系数据
我正在学习railcast教程,学习如何使用GemRoo使用excel文件将数据导入数据库。导入和导出数据工作正常,但在导入关系数据时,会显示以下错误:Ruby on rails 如何从excel文件导入关系数据,ruby-on-rails,ruby-on-rails-4,roo,Ruby On Rails,Ruby On Rails 4,Roo,我正在学习railcast教程,学习如何使用GemRoo使用excel文件将数据导入数据库。导入和导出数据工作正常,但在导入关系数据时,会显示以下错误: unknown attribute 'PzaXCja' for Producto. Extracted source (around line #73): row = Hash[[header, spreadsheet.row(i)].transpose] producto = find_by_Clave(row["C
unknown attribute 'PzaXCja' for Producto.
Extracted source (around line #73):
row = Hash[[header, spreadsheet.row(i)].transpose]
producto = find_by_Clave(row["Clave"]) || new
producto.attributes = row.to_hash.slice(*row.to_hash.keys)
producto.save!
end
end
以下是我在模型producto中的方法:
has_one :productosxpza, class_name: "Productosxpza", foreign_key: "Producto"
accepts_nested_attributes_for :productosxpza
def self.to_csv(options = {})#exportar
CSV.generate(options) do |csv|
csv << column_names
all.each do |producto|
csv << producto.attributes.values_at(*column_names)
end
end
end
def self.import(file)#importar
spreadsheet = open_spreadsheet(file)
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
producto = find_by_Clave(row["Clave"]) || new
producto.attributes = row.to_hash.slice(*row.to_hash.keys) #*row.to_hash.keys para rails 4 que sustituye el attr_accesible de rails 3
producto.save!
end
end
def self.open_spreadsheet(file)#importar
case File.extname(file.original_filename)
when '.csv' then Roo::Csv.new(file.path, packed: false, file_warning: :ignore)
#when '.xls' then Roo::Excel.new(file.path, packed: false, file_warning: :ignore)
when '.xlsx' then Roo::Excelx.new(file.path, packed: false, file_warning: :ignore)
#else raise "Unknown file type: #{file.original_filename}"
else raise "El formato debe ser .xlsx ó .csv"
end
end
如果我没弄错的话,你想在productosxpza上设置属性,但要通过producto,对吗?这应该行得通
producto.productosxpza_attributes = { ... }
请打印出变量行的内容,它可能不是producto.attributes={key:value}@HoMan的正确格式。该方法允许我创建具有关联的记录?@HoMan当我这样做时:producto.attributes={Clave:Clave}我得到以下错误:未初始化的常量Producto::clave键应该是属性名。因此,如果产品有一个名为name的属性,那么它应该是producto.attributes={name:'Clave'}@HoMan好的,谢谢。至于如何创建相关数据的问题,product有一个productoxpza。我尝试了以下操作:producto.attributes={Clave:row[Clave],PzaXCja:row[PzaXCja]},但我得到了以下错误:产品的未知属性“PzaXCja”。请更正它,导入相关表中的数据,但现在我上传一条现有记录时出现了一个小错误,它没有像以前那样更新它,但它向我发送了这个错误:无法将值NULL插入列'Producto',表'AdvanceControl_Copy.dbo.ProductosXPzas';列不允许空值。更新失败。:EXEC sp_executesql N'UPDATE[productosxpzas]SET[Producto]=@0其中[productosxpzas].[IDP]=@1;选择@ROWCOUNT AS AffectedRows',N'@0 varchar50,@1 int',@0=NULL,@1=165我尝试此操作以更新productosxpza:productosxpza=find_by_Productorow[Clave]| | new producto.productosxpza_属性={PzaXCja:row[PzaXCja],producto:row[Clave]}producto.save!productosxpza中的producto是外键,但我得到了相同的错误