gpt4 book ai didi

mysql - 如何使用 rails 将 excel 文件导入 mysql?

转载 作者:行者123 更新时间:2023-11-30 22:51:05 29 4
gpt4 key购买 nike

我有模型元素

id | category_id | name | description | price | wall_th | size |

元素.rb

has_many :item_gosts
has_many :gosts, through: :item_gosts
has_many :item_steel_marks
has_many :steel_marks, through: :item_steel_marks

2个连接表item_gosts 和 item_steel_marks

并拥有包含此数据的 xlsx 文件

| name     | |size  | |Gosts    |  |steel marks | description | |price |
|steel tube| |45x4 | |8734;8732| |3сп; 20; 10 | L = 5-10,5 | |257664|

如果在文件 Gosts param = item_gosts 和 steel marks params(3сп; 20; 10) for item_steel_marks 中,如何将此文件导入带有连接表的 mysql?

最佳答案

我会将它导出到 csv,然后编写一个 rake 任务,从 csv 创建所有模型。类似的东西:

require 'csv'

desc "Load Items"
task :load => :environment do
CSV.foreach(MY_CSV_FILENAME, headers: true) do |row|
row = row.to_hash.symbolize_keys
Item.create(row)
end
end

编辑:对于连接表,我假设您可以将 Excel 分成 5 个表:Items、ItemGosts、Gosts、ItemSteelMarks 和 SteelMarks。然后将它们全部放入单独的 csv 文件中,并大致执行如下操作:

require 'csv'

desc "Load"
task :load => :environment do
create_models(MY_ITEM_CSV, Item)
create_models(MY_GOST_CSV, Gost)
create_models(MY_STEEL_MARKS_CSV, Steel)
create_joins(MY_ITEM_GOSTS_CSV, :gosts, Gost, :gost_id)
create_joins(MY_ITEM_STEEL_MARKS_CSV, :steel_marks, SteelMarks, :steel_mark_id)
end

def create_models(filename, model)
foreach_table_row(filename) { |row| model.create(row) }
end

def create_joins(filename, relation, model, model_id)
foreach_table_row(filename) do |row|
item = Item.find_by(id: row[:item_id])
item.send(relation) << model.find_by(id: row[model_id])
item.save
end
end

def foreach_table_row(filename)
CSV.foreach(filename, headers: true) do |row|
yield row.to_hash.symbolize_keys
end
end

关于mysql - 如何使用 rails 将 excel 文件导入 mysql?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28137942/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com