我是Ruby on Rails的新手,我有一个cron作业,可以从我的供应商那里获取一个类别列表CSV。有了列表后,我将列添加到我的数据库中,在本例中是MongoDB。
我想以可读和可导航的格式重现结构。我已经看过有关Mongo Tree等的详细信息,但我不确定是否可以这样做。
模型
class Category
include Mongoid::Document
field :category_id, :type => Integer
field :category_name
field :category_description
field :category_parent, :type => Integer
end
Cron任务
def categories
categoriesHash = HTTParty.get('http://feed.suuplier.com/user=xxxx&format=csv')
categoriesCSV = categoriesHash.parsed_response
categoriesCSV.each_with_index do |item, i|
if i != 0
Category.find_or_create_by(category_id: item[0]) do |category|
category.category_id = item[0]
category.category_name = item[1]
category.category_parent= item[2]
category.save
end
end
end
CSV
Category ID Category Name Category Parent Id
4 Electronics 0
5 Audio Equipment 4
6 Home Entertainment 4
7 Photography 4
8 Portable Audio 4
9 Televisions 4
10 Amplifiers & Receivers 5
11 Audio Systems 5
12 Cassette Decks 5
13 CD Players 5
14 Radios 5
15 HiFi Speakers 5
17 MiniDisc Separates 5
18 Tuners 5
19 DJ Equipment 5
结果必须是:
Electronics
--- Audio Equipment
------ Amplifiers & Receivers
------ Audio Systems
------ Cassette Decks
------ CD Players
------ Radios
------ HiFi Speakers
------ MiniDisc Separates
------ Tuners
------ DJ Equipment
--- Home Entertainment
--- Photography
--- Portable Audio
--- Televisions
我可以简单地循环,但我不知道是否有更有效的方法。