Basic tagging with ActiveRecord
  • There are gems for tagging but I find for simple cases they're unnecessary.

  • Setup

  • Create two models:

  • rails g model tag name:text
  • rails g model tag_instance tag_id:integer item_id:integer item_type:string
  • Add relationships to your TagInstance model

  • belongs_to :tag
    belongs_to :item, polymorphic: true
    
    validates_uniqueness_of :tag_id, scope: [:item_id, :item_type]
  • Adding tag-ability to a model

  • Now, in any other model, to enable tagging you just have to add

  • has_many :tag_instances, as: :item
    has_many :tags, through: :tag_instances
  • Usage

  • Add a tag to any object with this two-liner

  • post = Post.last
    tag = Tag.find_or_create_by(name:"My Tag")
    post.tags << tag unless post.tags.exists?(tag.id)
  • Find all objects with a particular tag with this

  • Post.joins(:tags).where("tags.name = ?","My Tag")

  • Website Page