从现有属性分配 parent_id
assigning parent_id from an existing attribute
我有一个从 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.new(:assembly_level=> 参数[:parent_id])
假设您正在逐行读取 CSV 文件中的内容以及您提供的少量信息,我认为(如果我错了请纠正我)层次结构隐含在文件的顺序中。
我会试试这个:
- 无论何时存储记录,都会将记录的 ID 存储在一个临时变量中。
- 然后,我会检查下一条记录是否是 children。如果是这样,我将分配我刚刚存储的 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
我有一个从 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.new(:assembly_level=> 参数[:parent_id])
假设您正在逐行读取 CSV 文件中的内容以及您提供的少量信息,我认为(如果我错了请纠正我)层次结构隐含在文件的顺序中。
我会试试这个:
- 无论何时存储记录,都会将记录的 ID 存储在一个临时变量中。
- 然后,我会检查下一条记录是否是 children。如果是这样,我将分配我刚刚存储的 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