How to declare tags aliases with acts_as_taggable_on in Rails?
Asked Answered
D

2

7

The acts_as_taggable_on implementation worked quite well, but I also need to declare tags aliases.

I've found a plugin that claimed to do so, acts_as_taggable_with_aliases, but last commit was in 2009 and is not on the gem repositories, so I assume the project is dead by now.

There is any way to achieve this?

Ducky answered 11/8, 2011 at 21:13 Comment(1)
Did you look at the source to see how _with_aliases did it?Faruq
U
1

Maybe you can create your own models to support this (and anything else you want)...

I think you can achieve that by doing something like:

class Tag < ActiveRecord::Base
end

class Tagging < ActiveRecord::Base
    validates_presence_of :tag_id
    belongs_to :tag
    belongs_to :taggable, :polymorphic => true
end

class ModelIWantToBeTagged < ActiveRecord::Base
  include ModelTagging
  has_many :taggings, :as => :taggable
end

module ModelTagging
    def add_tag(tag_name)           
        tag = Tag.find_or_create_by_tag(tag_name)
        tagging = Tagging.new
        tagging.taggable_id = self.id
        tagging.taggable_type = get_class_name
        tagging.tag_id = tag.id
        tagging.save!
    end

    def remove_tag(tag_name)
        tag = Tag.find_by_tag(tag_name)         
        Tagging.where(:tag_id => tag).delete_all        
    end

    private
    def get_class_name
        self.class.name
    end
end

This way you can any behavior and data to your tags.

Hope it helps you!

Unmoor answered 15/5, 2012 at 12:55 Comment(0)
M
0

You can take a look to the code of acts_as_taggable_with_aliases. All is inside. You can see if it's allways compatible with acts_as_taggable and check if you can try maintain it.

Madai answered 3/4, 2012 at 8:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.