我有一个模型文章 在mydb
+----+------------------------+
| id | keywords |
+----+------------------------+
| 83 | automotive, pet, heath |
| 82 | car, plane |
| 81 | NULL |
| 80 | pet, car |
| 78 | Null |
+----+------------------------+
我希望得到的结果与:
相同{
"automotive" => [82],
"pet" => [82,80],
"heath" => [83],
"plane" => [82],
"car" => "80"
}
我如何获得与上述数据相同的结果?
答案 0 :(得分:0)
基本上,将关键字设置为哈希的键,并将insert article id保存到相应的数组
中summary = Hash.new()
Article.all.each do |a|
if a.keywords
# assuming your keywords is stored as a string
a.keywords.split(", ").each do |keyword|
if summary[keyword].empty?
summary[keyword] = [a.id]
else
summary[keyword].push(a.id)
end
end
end
end