ActiveRecord 更好的、非数字和非顺序的 id

Posted

技术标签:

【中文标题】ActiveRecord 更好的、非数字和非顺序的 id【英文标题】:Better, non numerical and non sequencial ids for ActiveRecord 【发布时间】:2014-09-18 13:24:14 【问题描述】:

我在我的 Rails 4.1.1 应用程序中使用 ActiveRecord,我将对象保存在数据库中,但我真的不喜欢分配给我的对象的 id(1、2、3 等)我想要这些 id是非整数和非序列的,就像 MongoId gem 一样。

我该怎么做?

【问题讨论】:

您使用的是什么数据库?你到底想让他们成为什么? GUID? 【参考方案1】:

我假设您希望进行此更改,因为您不喜欢 id 在 url 中的公开方式...

http://my_application.com/posts/3.html

没有其他理由更改 id...他们做他们应该做的工作并且他们(上述情况除外)在应用程序内部。

您可能要考虑的技术是使用“slugs”

在您的模型中创建一个名为 slug 的属性,它可以是您的模型“标题”或“名称”,但采用 url 友好格式...在 before_save 操作中自动创建它

class Post < ActiveRecord::Base
  before_save :create_slug

  def create_slug
    #strip the string
    slug = title.strip

    #blow away apostrophes
    slug.gsub! /['`]/,""

    # @ --> at, and & --> and
    slug.gsub! /\s*@\s*/, " at "
    slug.gsub! /\s*&\s*/, " and "

    #replace all non alphanumeric, underscore or periods with underscore
     slug.gsub! /\s*[^A-Za-z0-9\.\-]\s*/, '_'  

     #convert double underscores to single
     slug.gsub! /_+/,"_"

     #strip off leading/trailing underscore
     slug.gsub! /\A[_\.]+|[_\.]+\z/,""

     #make sure the slug is unique...
     unique = false
     appendix = ""
     counter = 0
     until unique
       test_slug = slug + appendix
       test_object = self.class.find_by_slug(test_slug)
       unique = true unless test_object && test_object != self
       counter += 1
       appendix = "_#counter"
     end

     self.slug = test_slug
  end
end

然后在你的类中创建一个 'to_param' 方法...这将创建将出现在 url 中的“user_friendly” id

def to_param
  slug
end

最后,您需要将“find”方法替换为“find_by_slug”(以便它搜索 slug,而不是原始 id)

@post = Post.find_by_slug(params[:id])

所有这些都会给你一个更好的 url...

http://my_application.com/posts/my_post_about_flowers.html

这是关于 slugging 的一个很好的参考 http://blog.teamtreehouse.com/creating-vanity-urls-in-rails

我展示的 slug 方法改编自这篇 SO 帖子...

Best way to generate slugs (human-readable IDs) in Rails

【讨论】:

以上是关于ActiveRecord 更好的、非数字和非顺序的 id的主要内容,如果未能解决你的问题,请参考以下文章

线程和非线程函数调用的执行顺序是啥?

聚集索引和非聚集索引的区别

Rails - has_one 关系:关联和非关联对象的范围

多线程学习 公平锁和非公平锁

聚集索引和非聚集索引

聚集索引和非聚集索引(转)