Search code examples
ruby-on-rails-3mongodbmongoidtagging

Good solution for tagging in Rails with MongoID


What are good solutions for tagging in Rails with MongoID?

It seems that it is really simple to just add a hash or array to a document, but I am not sure if that is the best approach.

Maybe some Gem? Or a simple trick with nested documents?


Solution

  • For now, I used a very simple approach, that works very well: Just include an Array-field.

    #app/models/image.rb
    class Image
      include Mongoid::Document
      include Mongoid::Timestamps
    
      field :message, :type => String
      field :tags, :type => Array
    
      def self.images_for tag
        Image.any_in(:tags => [tag])
      end
    end
    
    #routes.rb
    match "tag/:tag" => "images#tag"
    
    #/app/controller/images_controller.rb
    class ImagesController < ApplicationController
      # GET /tag
      # GET /tag.xml
      def tag
        @images = Image.images_for params[:tag]
    
        respond_to do |format|
          format.html { render "index" }
          format.xml  { render :xml => @images }
        end
      end
    end
    

    This works, but I am a still a little doubtfull about the performance of the Image.any_in map/reduce. I think there may be a better solution for that map/reduce but have not found it, yet.