我有一个从CSV文件导入的数据库,我想根据下面的汇编级别分配层次结构。不知道该采取哪种方法。我可以写if语句,但是会很长。对不起,我是新手,我不知道从哪里开始。如有任何帮助,不胜感激。
assembly_level assembly_tree description uniq_id
0 zero level "zero level" d9s64
1 level one assembly "level one" c9633
2 level two assembly "level two" 11197
3 level three assembly "level three" e271f
4 level four assembly "level four" 552da
4 level four assembly "level four" 4568a
3 level three assembly "level three" b72bd
我如何在导入期间分配assembly_level给Parent_id ?
@item = Item。新(:assembly_level => params [: parent_id])
假设您正在从CSV文件中导入逐行读取的内容和您提供的少量信息,我认为(如果我错了请纠正我)层次结构隐含在文件的顺序中。
我想试试这个:
- 无论何时存储一条记录,都将记录的id存储在一个临时变量中。
- 然后,我会检查下一个记录是否为儿童。如果是这样,我将分配我刚刚存储的parent_id。
一个未经验证的代码样本,所以你可以看到我在想什么:
previous_record['id'] = 0
previous_record['level'] = 999 # Temp variable with previous record
csv_file.read do |line| # Reading method of your choice
line_array = line.split(";")
item = Item.new({'assembly_level' => line_array[0], 'assembly_tree' => line_array[1], 'description' => line_array[2], 'uniq_id' => line_array[3]) # Creating regular item
# If the current item is children the assembly level is greater than the previous one
if item.assembly_level > previous_record['level']
item.parent_id = previous_record['id']
item.save
else # Only store previous value when is not a children
# Storing values to use for the next record
previous_record['id'] = line_array[3]
previous_record['level'] = line_array[0]
end
end