【问题标题】:Is there a way for mongoid to use integer(number) as a default id rather than long hash value?有没有办法让 mongoid 使用整数(数字)作为默认 id 而不是长哈希值?
【发布时间】:2011-06-03 02:24:39
【问题描述】:

我只想拥有 ActiveRecord 的默认特性,它使用增量整数作为 id 来减少 url 的长度。

例如,创建的第一篇文章将具有类似“app.com/articles/1”的 URL,这是 ActiveRecord 中的默认值。

在 mongoid 中是否有任何 gem 支持此功能?

【问题讨论】:

    标签: ruby-on-rails ruby mongoid


    【解决方案1】:

    您总是可以生成更短、唯一的标记来识别您的每条记录(作为 slugging 的替代方法),因为您的目标只是减少 URL 的长度。

    我最近(今天)写了一个 gem - mongoid_token,它应该可以消除为您的 mongoid 文档创建唯一令牌的任何艰苦工作。它不会按顺序生成它们,但它应该可以帮助您解决问题(我希望!)。

    【讨论】:

    • 如何为我的文档重新生成令牌?更具体地说,如何为我在添加 Mongoid::Token 之前创建的现有文档生成令牌,现在具有令牌值 nil
    【解决方案2】:

    你可以试试这样的:

    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
    

    我没有完全尝试过这种方法(将它与内部 id 一起使用),但我很确定它应该可以工作。在这里查看我的应用程序: https://github.com/daekrist/Mongologue 我在帖子和评论模型中添加了名为 pid 的“可见”id。我也将文本 id 用于标记模型。

    【讨论】:

    • .inc 的语法现在是:@seq.inc(last_id: 1)(仅接收 1 个参数)
    【解决方案3】:

    【讨论】:

    • 还有mongoid-slug,这是一个很好的mongoid slugging扩展。
    • 不错!不知道这个。
    • 其实我已经在用mongoid-slug了,把文章标题设置为key。问题是标题是非拉丁字符,而 mongoid-slug 将标题翻译成更长的字母字符串……我不喜欢……
    猜你喜欢
    • 2021-06-20
    • 2021-07-23
    • 2023-02-14
    • 2020-02-03
    • 1970-01-01
    • 2021-11-01
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多