acts_as_taggable on many instances

85 Views Asked by At

Here's the example:

@profiles = Profile.where(something: true)

Instead of doing:

@profiles.each do |profile|
  @some_user.tag(profile, :with => "paris, normandy")
end

Is there a way to tag all the instances of a model in one call, like this?:

@some_user.tag(@profiles, :with => "paris, normandy")
1

There are 1 best solutions below

0
tirdadc On

I don't think there's anything out of the box to do this, but look at directly using the Tagging model to do bulk tag assignment if you're concerned about performance / speed.

Here's an adaptation of the code there for your use case, you still need to provide profile_ids and tag_ids.

Tagging.transaction do
  profile_ids.each do |pid|
    tag_ids.each do |tid|
      values = ["Profile", pid, tid].join(", ")
      Tagging.connection.execute "INSERT INTO taggings (taggable_type, taggable_id, tag_id) VALUES (#{values}) ON DUPLICATE KEY UPDATE id=id"
    end
  end
end