views:

25

answers:

1

I'm using acts_as_taggable_on in my Rails app, and I'd like advice on the best way to merge two tags.

For example, if I've got a list of Food records, and some are tagged "cheese" and some are tagged "milk," what's the best way to combine these tags into a single "dairy" tag. Should I just find all records tagged with "cheese" and/or "milk," tag those records with the new "dairy" tag, and delete the "cheese" and "milk" tags and taggings, or is there a better way to do this?

I've looked in the gem's docs and specs, and I don't see any dedicated method that would combine multiple tags. If I go the multi-step route I propose above, do I run any risk of messing up the taggings if one of the steps fails (if some records don't become tagged with "dairy" for whatever reason and the "cheese" tags are "deleted)?

A: 

If you want to make sure that no tags are changed unless all the changes are successful, use a database transaction. The code would look something like this:

Food.transaction do
  Food.tagged_with('milk', 'cheese').each do |food|
    food.tag_list -= ['milk', 'cheese']
    food.tag_list << 'dairy'
    food.save!
  end
end
Dave Pirotte