Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 526
user482594 Avatar asked Jun 03 '11 02:06

user482594


2 Answers

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!).

like image 78
theTRON Avatar answered Sep 23 '22 12:09

theTRON


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.

like image 45
Jake Jones Avatar answered Sep 24 '22 12:09

Jake Jones