【发布时间】:2011-06-03 02:24:39
【问题描述】:
我只想拥有 ActiveRecord 的默认特性,它使用增量整数作为 id 来减少 url 的长度。
例如,创建的第一篇文章将具有类似“app.com/articles/1”的 URL,这是 ActiveRecord 中的默认值。
在 mongoid 中是否有任何 gem 支持此功能?
【问题讨论】:
标签: ruby-on-rails ruby mongoid
我只想拥有 ActiveRecord 的默认特性,它使用增量整数作为 id 来减少 url 的长度。
例如,创建的第一篇文章将具有类似“app.com/articles/1”的 URL,这是 ActiveRecord 中的默认值。
在 mongoid 中是否有任何 gem 支持此功能?
【问题讨论】:
标签: ruby-on-rails ruby mongoid
您总是可以生成更短、唯一的标记来识别您的每条记录(作为 slugging 的替代方法),因为您的目标只是减少 URL 的长度。
我最近(今天)写了一个 gem - mongoid_token,它应该可以消除为您的 mongoid 文档创建唯一令牌的任何艰苦工作。它不会按顺序生成它们,但它应该可以帮助您解决问题(我希望!)。
【讨论】:
Mongoid::Token 之前创建的现有文档生成令牌,现在具有令牌值 nil
你可以试试这样的:
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 个参数)
AFAIK 设计不可能: http://groups.google.com/group/mongoid/browse_thread/thread/b4edab1801ac75be
所以社区采取的方法是使用slugs: https://github.com/crowdint/slugoid
【讨论】: