帮助创建一个数组

时间:2011-08-22 10:25:31

标签: ruby-on-rails arrays activerecord

我有一个类别模型。

attr_accessible :name, :parent, :tags, :active, :image

示例数据类似于

"Bakery",null,"bakehouse, baker, bakeries, bakers, bakery, bakeshop, biscuit factory, boulangerie,  bread bakery, bread, cake bakery, cake topper, cake toppers, cake, cakes, confectionery, cook shop, pastry kitchen, pastry shop, pastry, patisserie, wedding cake", 1, null
"Beauty & Makeup",null,"makeup, ", 1, null

执行@categories = Category.all为我提供了包含所有字段的所有类别,现在我想创建一个带有标签和类别名称的数组。数组数据应该像

[["Bakery", "bakehouse"]
["Bakery", "baker"]
["Bakery", "bakeries"]
["Bakery", "bakers"]
["Bakery", "bakery"]
.....
["Beauty & Makeup", "makeup"]]

怎么办呢?

1 个答案:

答案 0 :(得分:2)

@categories.map {|cat| cat.tags.split(/, /).map {|tag| [cat.name, tag]}}应该可以解决问题。