ruby-on-railsacts-as-taggable-on

Rails 5 Postgres - replace all resource with one tag with multiple tags?


I recently migrated over a bunch of models to one umbrella model, and the issue is that the tag_list for all the old models migrated over as a long string, rather than delimited tags.

For example:

Post.tag_list = "popcorn, salty, butter" 

came over to the new model as:

"popcorn salty butter"

I have this SQL migration in rails

execute("UPDATE tags SET name='popcorn, salty, butter' WHERE LOWER(name) LIKE 'movie popcorn' ESCAPE '!';")

This works, but my rails app is replacing all resources with the tag movie popcorn with one LONG string -> "popcorn, salty, butter", when i just want popcorn, salty, butter - note the double quotations (I don't want the double quotation mark string, as my app uses commas as the delimiter to indicate multiple tags)

I want to replace all resources that have the tag(s) movie popcorn with three tags instead: popcorn, salty and butter - How can i do that with the above code? Since it's working similarly, but adding in double quotation marks, which does not allow the app to function for tag searching.

I am using acts as taggable and rails 5.1.6.


Solution

  • Instead of renaming tag, it’s necessary to create tags popcorn, salty and butter, each as a single record of tags table, and then update your resources. Single-runner for this can look like:

    tags = %w[popcorn salty butter].map do |tag|
      Tag.find_or_create_by(name: tag)
    end
    Post.joins(:tags).where("tags.name = 'movie popcorn'").each do |post|
      post.tags = tags
    end
    

    Migrations won't help there.

    UPDATE: In case of using acts_as_taggable_on gem the code will look like:

    Post.tagged_with('movie popcorn').each do |post|
      post.tag_list = "popcorn, salty, butter"
      post.save
    end