user482594
user482594

Reputation: 17486

Is there a way for mongoid to use integer(number) as a default id rather than long hash value?

I just want to have default characteristic of ActiveRecord which uses incremental integers as id to reduce the length of the url.

For example, first article created will have url like "app.com/articles/1" which is default in ActiveRecord.

Is there any gem that supports this in mongoid?

Upvotes: 7

Views: 4189

Answers (3)

Jake Jones
Jake Jones

Reputation: 1170

You can try something like this:

class Article
  include Mongoid::Document
  identity :type => Integer
  before_create :assign_id

  def to_param
    id.to_s
  end

  private

    def assign_id
      self.id = Sequence.generate_id(:article)
    end
end

class Sequence
  include Mongoid::Document
  field :object
  field :last_id, type => Integer

  def self.generate_id(object)
    @seq=where(:object => object).first || create(:object => object)
    @seq.inc(:last_id,1)
  end
end

I didn't try such approach exactly (using it with internal ids), but I'm pretty sure it should work. Look at my application here: https://github.com/daekrist/Mongologue I added "visible" id called pid to my post and comment models. Also I'm using text id for Tag model.

Upvotes: 3

theTRON
theTRON

Reputation: 9659

You could always generate shorter, unique tokens to identify each of your records (as an alternative to slugging), since your goal is just to reduce the length of the URL.

I've recently (today) written a gem - mongoid_token which should take any of the hard work out of creating unique tokens for your mongoid documents. It won't generate them sequentially, but it should help you with your problem (i hope!).

Upvotes: 6

Roman
Roman

Reputation: 13058

AFAIK it's not possible by design: http://groups.google.com/group/mongoid/browse_thread/thread/b4edab1801ac75be

So the approach taken by the community is to use slugs: https://github.com/crowdint/slugoid

Upvotes: 2

Related Questions