我正在尝试做一个简单的小写并删除rails中的重复项。也保存到数据库。
Tag.all.each do |tag|
tag_name = tag.name.downcase!
tag_name.uniq!
tag.save!
end
错误
NoMethodError: undefined method `uniq!' for nil:NilClass
还尝试了采摘
tag_name = Tag.pluck(:name)
tag_name.each do |tag|
name = tag.downcase!
name.uniq!
end
错误
NoMethodError: undefined method `uniq!' for nil:NilClass
答案 0 :(得分:0)
使用group_by查找过滤器查询。
found_tags = Tag.all.group_by { |tag| tag.name.downcase }
found_tags.each do |key, val|
if found_tags[key].count > 1
tag_to_keep = val.shift
val.each do |t|
t.taggings.update_all(tag_id: tag_to_keep.id)
t.destroy!
end
tag_to_keep.update(name: tag_to_keep.name.downcase)
end
end