在rails中分组和过滤



我有一个模型文章

+----+------------------------+
| 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" 
}

我如何得到与上面数据相同的结果??

基本上,将关键字设置为哈希的键,并保持插入文章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

相关内容

  • 没有找到相关文章

最新更新