开发者

How to declare tags aliases with acts_as_taggable_on in Rails?

开发者 https://www.devze.com 2023-03-27 06:18 出处:网络
The acts_as_taggable_on implementation worked quite well, but I also need to declare tags aliases. I\'ve found a plugin开发者_StackOverflow中文版 that claimed to do so, acts_as_taggable_with_aliases,

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

I've found a plugin开发者_StackOverflow中文版 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?


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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号