简体   繁体   English

更强大的活动记录ID

[英]Stronger Active Record IDs

How can we get Active Record to create more complex IDs that are not just the natural numbers (1, 2, 3 ...). 我们如何获得Active Record来创建更复杂的ID,而不仅仅是自然数(1、2、3 ...)。 I'm not sure if I should be using database IDs to identify objects, but I am now and it would be pretty insecure to have them like this in production. 我不确定是否应该使用数据库ID来标识对象,但是现在,要在生产环境中使用这样的对象将是非常不安全的。

Lets just say you want to use a column called slug for an object called Post . 假设您要对名为Post的对象使用称为slug的列。

  • Create a slug column for that table 为该表创建一个slug
  • Create a before_create method in Post model that will generate a unique slug value before saving the record. 创建before_create的方法Post模型,将生成一个唯一的slug保存记录之前的值。 Maybe do some checking to ensure it's unique 也许做一些检查以确保它是唯一的
  • Replace anything that's public facing to use Post.find_by(slug: id) instead of Post.find(id) . 替换所有面向公众的内容,以使用Post.find_by(slug: id)代替Post.find(id)
  • Ensure any url generation will use something like this: post_path(id: post.slug) so that it won't put the id the URL. 确保任何url生post_path(id: post.slug)将使用以下内容: post_path(id: post.slug)以便不会将id放在URL中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM