从现有属性中分配parent_id

时间:2015-06-01 06:51:40

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2

我有一个从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 => params [:parent_id])

1 个答案:

答案 0 :(得分:0)

假设您要逐行输入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