Search code examples
ruby-on-railsacts-as-taggable-on

Rails - Make model without database taggable


I have a tableless model like this:

class Wiki 
    include ActiveModel::AttributeMethods
    include ActiveModel::Validations
    include ActiveModel::Conversion
    extend ActiveModel::Naming

    # No Database
    def persisted?
        false
    end
    # ...
end

When I claim acts_as_taggable in this model, I got undefined local variable or method 'acts_as_taggable' for it. However I tried include ActiveModel::Model, it still doesn't work. Any ideas I can make my tableless model be taggable?


Solution

  • As you can see from the source code of the plugin, it requires that you use it with AR. It includes itself into ActiveRecord::Base.

    So, you may want to add those into your class as well, like so:

    class Wiki 
        include ActiveModel::AttributeMethods
        include ActiveModel::Validations
        include ActiveModel::Conversion
        extend ActiveModel::Naming
    
        # Adding `acts_as_taggable`
        extend ActsAsTaggable::Taggable
        include ActsAsTaggable::Tagger
    
        # No Database
        def persisted?
            false
        end
        # ...
    end
    

    But!

    But, then again, you will have to include more AR modules to make it work. Since, the gem requires that your class AR specific methods that are available in ActiveRecord::Base class, such as has_many, etc.

    For example here:

    has_many :taggings, :as => :taggable, :dependent => :destroy, :include => :tag, :class_name => "ActsAsTaggable::Extra::Tagging"
    has_many :base_tags, :through => :taggings, :source => :tag, :class_name => "ActsAsTaggable::Tag"