Thanks! That was exactly what I needed!
I only needed to make a minor change and add if topic.tags.exclude?(tag) on the if statement to avoid duplicates.
Here’s what I used for future reference:
tag = Tag.find_by(name: 'TAG')
category = Category.find_by(name: 'CAT_NAME')
Topic.where(category: category).each do |topic|
if topic.tags.exclude?(tag) && topic.first_post.raw =~ /<your keyword here>/
topic.tags << tag
end
end